Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter Highchart plot Data based on Many-to-One relationship?
I have this App where I'm showing some data using Highchart (just an example here). The data is based on a History table where I have product_id, year, quantity (I want to show the Quantity over Time). In my model I also have a table for Products with products, category (each product has a category, multiple products can share the same category). The two tables have a one-to-many relationship with the field product. In my template I'd like the user to be able to filter the products by the category field (ie: filter products with category 'A'), and this filter should also update the Chart (ie: I want to see the history for just the products in category 'A'). Below my code, I've tried many attempts but none has worked so far. Please let me know if the code has all the info you need, I've tried to take just the essential. models.py class Products(models.Model): product = models.TextField(primary_key=True) category = models.TextField(blank=True,null=True) # ... class HistoryProducts(models.Model): product_id = models.ForeignKey(Products) year = models.TextField(blank=True, null=True) quantity = models.DecimalFeld(..) # ... filters.py import django_filters class ProductsFilter(django_filters.FilterSet): category_contains = CharFilter(field_name='category', lookup_expr='icontains') views.py def index(request): myFilter = ProductsFilter(request.GET, queryset=Products) products = myFilter.qs # ... return render(request, … -
Why does my Django form validation always return false rather than true?
I have a form which is extended by ReCaptcha and Giphy.com gifs for blog post comments. No matter how I fill in the data, the form always returns false. This is the log of print(form.errors): <ul class="errorlist"><li>captcha<ul class="errorlist"><li>This field is required.</li></ul></li></ul> CommentForm # Blog Post Comment Form class CommentForm(forms.ModelForm): captcha = ReCaptchaField( widget=ReCaptchaV2Checkbox( attrs={ 'data-theme': 'light', } ) ) # Docu https://github.com/praekelt/django-recaptcha class Meta: model = Comment fields = ('name', 'text') post_comment view from django.views.decorators.http import require_http_methods @require_http_methods(['POST']) def post_comment(request): if request.POST: form = CommentForm(request.POST) print(form.errors) # Log see top of post if form.is_valid(): # the form is never considered valid.. print('valid') gif = request.POST['gif_src'] name = request.POST['name'] text = request.POST['text'] post_id = request.POST['post_id'] # Query all comments including the new one post = get_object_or_404(Post, id=post_id) comment = Comment.objects.create( post_id=post_id, name=name, text=text, gif=gif ) return render(request, 'post.html', {'post': post}) else: print('invalid') return render(request, 'post.html') Comment Model class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=200) text = models.TextField() gif = models.CharField(max_length=1000) created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=True) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text So what's going on at the validation that it always returns false? Even if I solve the captcha. some visualization of the … -
Running selenium tests in my digital ocean droplet does not work | SessionNotCreatedException: Message: Unable to find a matching set of capabilities
I'm following a tutorial in Harry Percival's book, Obey the testing goat. I really can't make this work despite trying to answers provided in stackoverflow. I have the latest version of selenium and geckodriver in my server. geckodriver is installed in /usr/local/bin I'm also a bit confused if I'm going to have firefox installed in the droplet or it will be called in my local machine. whenever I run my test in the server, the first error in the stacktrace tells something about this File "/home/elspeth/sites/staging.testdrivenlist.site/source/functional_tests/tests.py", line 41, in setUp self.browser = webdriver.Firefox() That's why I believe it can't really start firefox since it really can't. I have the same code in my local machine and the tests run but if i run it in the digital ocean server, it does not. Please help. -
Django-graphene multiple types for the same model
I have a quite big graphene-django API which feeds two applications. My first approach to restrict access to some fields was to have multiple DjangoObjectTypes for the same model, and use fields to limit which fields can be accessed on each type. Example for Organization: class OrganizationType(DjangoObjectType): class Meta: model = Organization fields = ( "id", "name", "members" "date_created", "last_modified", ) class LiteOrganizationType(DjangoObjectType): class Meta: model = Organization fields = ( "id", "name", ) Is this the best approach or should I have only one type and resolve fields based on the current user/app/etc..? The main issue I have experienced is that I need to explicitly define which type to use then in other related types. Thanks in advance! -
How to work with uploaded file using Django
I have Optical Character Recognition (OCR) project. I am generating an API using Django Framework. The API should look like as below: { "id": 1, "title": "PDF Title", "input": "input.pdf", "output": "output.pdf" } My models.py file as below: from django.db import models from .create_pdf_output import * # Create your models here. class Document(models.Model): title = models.CharField(max_length=255) pdf_input = models.FileField(upload_to='documents/inputs', max_length=200, blank=False) pdf_output = models.FileField(upload_to='documents/outputs', max_length=200, blank=True) def save(self): self.pdf_output = create_pdf_output(self.pdf_input) super(Document, self).save() def __str__(self): return self.title In models.py file I call create_pdf_file.py which should perform OCR operations on pdf input create_pdf_output.py import shutil import cv2 import numpy as np import img2pdf from pdf2image import convert_from_path import os def create_pdf_output(pdf_input): pdf = str(pdf_input) pdf_name = os.path.splitext(pdf)[0] + "_out.pdf" pages = convert_from_path(pdf_input, 500) if not os.path.exists('images'): os.mkdir('images') for ind, page in enumerate(pages): page.save(f'images/out{ind}.jpg', 'JPEG') for ind, img in enumerate(os.listdir('images')): img_rgb = cv2.imread(os.path.join('images', img)) img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY) template = cv2.imread('templates.jpg', 0) w, h = template.shape[::-1] res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED) threshold = 0.8 loc = np.where(res >= threshold) for pt in zip(*loc[::-1]): cropped_image = img_rgb[pt[1]:pt[1]+h, pt[0]:pt[0]+ 4*h] blurred = cv2.blur(cropped_image, (50,50)) img_rgb[pt[1]:pt[1]+h, pt[0]:pt[0]+ 4*h] = blurred if not os.path.exists('results'): os.mkdir('results') cv2.imwrite(f'results/res{ind}.jpg', img_rgb) dirname = 'images' with open(pdf_name, 'wb') as f: imgs … -
How to add or remove items with variations in an Order Summary page?
I have created a model for an item with variations s,m and l, when I add the same item with the different variations from the product detail page (such as item1 size Small and item1 size medium) it correctly adds the quantity for each item with different variation to the order summary page using a post method in the product detail page. Now in the Order Summary page when I try to add or remove the items with variations it is only updating to the 1st item added because it is reflected the item.slug not the item variations. To reclarify Adding the same item with different variations is working fine except that in the template order summary.html there is a tag with href to add to cart and remove a single item from cart which I think is the reason for the issue of not updating the quantity to the variant but updating to the item.slug, the addition to the cart is not reading variations. I have drawn arrows in the views and template where I think the reason for the error. I have also tried to add a post method in the order.summary.html template but it didn't work. (the … -
How to redirect from http://127.0.0.1:8000 to http://127.0.0.1:8000/login/ while starting the Django development server?
When I start Django development server, I am getting Page Not Found on http://127.0.0.1:8000/ as I have configured my login page URL in http://127.0.0.1:8000/login/. But I want to start my Django development server with http://127.0.0.1:8000/login so that I can see the login page directly and i dont need to put /login/ manually. Can anybody help me with this? -
Rating star drops after update page
I am new to django and I have a problem. I can display the number of stars in a movie but cannot remember this value graphically. HTML with Django <span class="rating"> {% for k, v in star_form.fields.star.choices %} <input id="rating{{ v }}" type="radio" name="star" value="{{ k }}"> <label for="rating{{ v }} ">{{ k }}</label> {% endfor %} {% endfor %} </span> <span class="editContent"> {% for rating in movie.rating_set.all %} //display rating {{ rating.star }} {% endfor %} </span> CSS .rating > label { position: relative; display: block; float: right; background: url('../images/star-off-big.png'); background-size: 30px 30px; } .rating > label:before { display: block; opacity: 0; content: ''; width: 30px; height: 30px; background: url('../images/star-on-big.png'); // stars on background-size: 30px 30px; transition: opacity 0.2s linear; } -
Reuse Python package in django
I would like to integrate a snipping tool in my django-app to take a screenshot and save it in my logo model. There is an existing python package doing this: https://github.com/harupy/snipping-tool. I`ve tryign to call this snipping tool from the html template based on another post How to execute python code by django html button? Problem: I am getting confused how to call the function from the html webpage and save it under the company_logo field part of the company model. Any directions would be appreciated. Many thanks, Current logo views.py from SnippingTool import SnippingWidget def take_snip(request): return render(request, 'company/company_detail.html') def output(request): if request.is_ajax(): py_obj = mycode.test_code(10) return render(request, 'company/company_detail.html', {'output': py_obj.a}) def logo_update(request, company_id): company= get_object_or_404(Company, pk=company_id) form = CompanyForm(request.POST or None, instance=company) if form.is_valid(): form.save() return render(request, 'company/company_detail.html', {'company': company}) else: form = LogoForm(instance=company) return render(request, 'company/logo_update.html', {'form': form}) models.py class Company(models.Model): company_logo = models.ImageField(default='logos/default_id.jpg', upload_to='logos', blank=True, null=True) company_detail.html <button id="myClickButton" type="button">Click</button> <div id="myOutput"></div> <script> $("#myClickButton").click(function() { $.get("/output/", function(take_snip) { $("#myOutput").html(take_snip); }, "html"); }); </script> <div class="col-sx-1 col-sm-5 "> <div class="row"> <a href="{% url 'company:company_update' company.id %}"> {% if company.company_logo %} <img src="{{ company.company_logo.url }}" width = "320" height = "100" style ="align-content: center;" class="img-rounded " > {% … -
Django child model data not saving with Ajax raising ValueError: Data didn't validate
I am trying to save data in a pair of related models in my Django application using Ajax. Though the parent table data is saved, I am unable to save data in the child model. The system gives off the following error message: Error: ValueError: The mappedTargFields could not be created because the data didn't validate. How do I save data in child table as well? Even with extensive search I am unable to find a solution to save inline formsets data (which I normally do using CBV + management form). Or is it not possible to save formset data using jQuery/Ajax? Given below are the relevant codes: views.py def SaveMapAjax(request, object_id=False): if request.method == 'POST' and request.is_ajax(): qs_targ_model_form = mappedTargModelForm(request.POST) target_field_formset = CreateMappedTargFieldsFormset(request.POST) if qs_targ_model_form.is_valid(): qs_targ_model_form.save() target_field_formset = CreateMappedTargFieldsFormset(request.POST, instance=qs_targ_model_form, prefix='') target_field_formset.save() msg='Data saved!!!' return JsonResponse(msg, safe=False) else: msg= 'Error occured in save!' else: qs_targ_model_form = mappedTargModelForm() target_field_formset = CreateMappedTargFieldsFormset(instance=qs_targ_model_form) return JsonResponse(msg, safe=False) Formset CreateMappedTargFieldsFormset = inlineformset_factory( mappedTargModel, # Parent table mappedTargFields, # Child table form=mappedTargFieldsForm, # Modelform on Child table extra=2, can_delete=False, min_num=1, validate_min=True) Template <!--html--> <form action="" method="POST" class="form" id="dataMapperForm"> {% csrf_token %} {{ target_model_form.as_p }} <div class="col-md-12 text-nowrap" style="font-family:'Courier New'"> {{ target_field_formset.management_form }} </div> </form> <!--The … -
Digital Signature with Token Stored in the Browser. (Django Framework)
Any idea how to do it? Is there a free software project I can guide you from? I need to make a system that can exchange files within it, and also that those documents that can be exchanged can be digitally signed by a token stored in the browser, more precisely, by the "eToken 5110" token. I am programming the system in Python with the Django Framework. Step by step: The system must be able to exchange files between authenticated users. In other words, a user can send, receive and delete a pdf file. And I need to add one more step, which seems a little more complex. User "X" can share a pdf file with "n" users, with n = 1, ..., 10; and that the same pdf document that has been shared with "n" users can be digitally signed, within the web app, by a token stored in a browser. Detail: If a pdf document is shared with "n" users, that document needs to be digitally signed, then it would be good if it cannot be accessed at the same time by more than one user. Note: The private key is stored in a cryptographic token called "eToken … -
Django: prefetch_related as list of objects
I dont know how to merge all refetch_related objects from MeasurememtResult table to one list objects: models.py class DeviceMeasurement(models.Model): patient = models.ForeignKey(Patient, blank=True, null=True, on_delete=models.CASCADE) device = models.ForeignKey(Device, on_delete=models.CASCADE) created_date = models.DateTimeField() front_id = models.UUIDField(blank=True, null=True) def __str__(self): return f'{self.device}' class MeasurememtResult(models.Model): measurement_result = models.FloatField() measurement_type = models.CharField(choices=MEASUREMENT_TYPES, max_length=30) device_measurement_id = models.ForeignKey(DeviceMeasurement, related_name='res_data', on_delete=models.CASCADE) views.py class GetMeasurements(viewsets.GenericViewSet, mixins.ListModelMixin): permission_classes = (IsAuthenticated,) serializer_class = GetMeasurementsSerializer queryset = DeviceMeasurement.objects.values('patient__first_name', 'device__id', 'created_date', 'front_id', 'results__measurement_result', 'results__measurement_type').prefetch_related('res_data').all() So, I got Response like as: [ { "created_date": "2020-06-05T15:03:22.481032+03:00", "front_id": null, "patient__first_name": "Alex", "device__id": 8, "results__measurement_result": 100, "results__measurement_type": "blood_pressure_SYS" }, { "created_date": "2020-06-05T15:03:22.481032+03:00", "front_id": null, "patient__first_name": "Alex", "device__id": 8, "results__t": 120, "results__measurement_type": "blood_pressure_DIA" } ] But I should return list of MeasurememtResult objects like as: In 2 objects i have equal values of device_id. { "created_date": "2020-06-05T15:03:22.481032+03:00", "front_id": null, "patient__first_name": "Alex", "device__id": 8, "res_data": [ { "results__measurement_result": 120, "results__measurement_type": "blood_pressure_DIA" }, { "results__measurement_result": 100, "results__measurement_type": "blood_pressure_SYS" } ] } -
Django 2.2 and Djongo Embedded Models - "Models aren't loaded yet"
Whenever I try to create an EmbeddedFieldin Django with Djongo I get the below error message. I tried everything suggested around the web. But I'm absolutely stuck here and need help to overcome that issue. As soon as I try to migrate it throws this error. This error starts to appear as soon as I use EmbeddedField. Error Message djongo django.core.expceptions.AppRegistryNotReady: Models aren't loaded yet. models.py from djongo import models class ClientRepresentation(models.Model): client_main_contact = models.CharField(max_length=100) client_stand_in_contact = models.CharField(max_length=100) class Meta: abstract = True class User(models.Model): client_name = models.CharField(max_length=100) client_location = models.CharField(max_length=100) client_representation = models.EmbeddedField( model_container=ClientRepresentation # null=True ) objects = models.DjongoManager() def __str__(self): return self.client_name settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # REST Framework API 'rest_framework', # Own Apps 'usr' ] -
Query Data across all child models of parent model
I'm working on a project with a parent class and multiple children class The parent class looks something like: class Item( VoteModel, PolymorphicModel, HitCountMixin ): sub_form = models.BooleanField( blank=True, default=False ) country = models.ForeignKey( Countries, null=True, on_delete=models.CASCADE ) top = models.BooleanField( blank=True, default=False ) in_moderation = models.BooleanField( blank=True, default=False ) sold = models.BooleanField( default=False ) out_of_stock = models.BooleanField( default=False ) title = models.CharField( max_length=500 ) category = models.ForeignKey( Category, null=True, on_delete=models.CASCADE ) location = models.ForeignKey( Location, null=True, on_delete=models.CASCADE ) and the child models look something like class VendorsItem( Item ): products = models.CharField( max_length=500,null=True ) price = models.PositiveIntegerField(null=True) per = models.CharField( max_length=500, null=True ) class FoodItem( Item ): experience = models.PositiveIntegerField( default=1,null=True ) agencies = models.CharField( max_length=500, default='Not Applicable',null=True ) price = models.PositiveIntegerField(null=True) per = models.CharField( max_length=500, null=True ) class MechanicsItem( Item ): experience = models.PositiveIntegerField( default=1 ,null=True) agencies = models.CharField( max_length=500, default='Not Applicable',null=True ) price = models.PositiveIntegerField(null=True) per = models.CharField( max_length=500, null=True ) class SalonBarberItem( Item ): experience = models.PositiveIntegerField( default=1,null=True ) agencies = models.CharField( max_length=500, default='Not Applicable',null=True ) price = models.PositiveIntegerField(null=True) per = models.CharField( max_length=500, null=True ) how could i get a value from a field from across 11 child models? -
Group By (or Filter By) within an Inline Model
So far, I have been successful regarding displaying the number of visits by a user on a specific endpoint. Let me show you the screenshot of an example. And below is the code snippet of this admin page. class UserCountInline(admin.StackedInline): model = Count readonly_fields = ('id','date_time') extra = 0 class UserAdmin(BaseUserAdmin): form = UserChangeForm add_form = UserCreationForm list_display = ('email', 'level', 'is_admin', 'is_active', 'user_counts') def user_counts(self, x): return x.counts.count() list_filter = ('is_admin',) fieldsets = ( (None, {'fields': ('email', 'password',)}), ('Personal info', {'fields': ('level',)}), ('Permissions', {'fields': ('is_admin', 'is_active',)}), ) inlines = (UserCountInline,) The problem is... my boss is still not happy with what I made. He stipulates that he must be able to access a group of count objects on a specific date. For example, if he chooses June 29 on a dropdown menu of the Counts inline, it will only show those counts created on June 29 so that he will enumerate the counts and charge his customer accordingly. I have been looking for such method all over the internet (especially SO) and I couldn't find such method other than some mentions about ForeignKey dropdown on some other model(not inline model). Is my boss's order a feasible request? Or should … -
Opening a user uploaded PDF in django
I have a webapp where a user can upload a pdf file. I want the user to be able to click a button to be able to see the file in the browser. I'm not sure how to link the pdfs as when they are uploaded they get given a random name by django in my static root. eg: hello_0akcjs.pdf My View def pdf_view(request, pk): Menufile = Menu.objects.get(pk=pk).menuFile with open('Menufile', 'r') as pdf: response = HttpResponse(pdf.read(), content_type='application/pdf') response['Content-Disposition'] = 'inline;filename=some_file.pdf' return response URL path('<int:pk>/', pdf_view, name='pdf_view'), Model class Menu(models.Model): name = models.CharField(max_length=50) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) menuFile = models.FileField(upload_to='menus') Template {% for menu in menus %} <a href="{% url 'pdf_view' menu.pk %}" class="btn btn-primary">View Menu {{ menu.name }}</a> {% endfor %} As it stands, everything works, except i just dont know how to get the pdf to be rendered at the URL for that model instances PK. -
Not able to insert data in second table in same DB in Django
I am using one db with 2 tables. Using template inheritance & I am able to insert data in one table from one template but not able to insert another data in another table from second template. While able to insert in db 'userdetails' but not able to insert data in 'logindb'. (Not sharing template from which able to insert data). If required will share. Help with be highly appreciated. **models.py** from django.db import models class user_details(models.Model): name = models.CharField(max_length=20) email = models.EmailField() mobile = models.CharField(max_length=20) category = models.CharField(max_length=10) member = models.BooleanField(default=False) query = models.CharField(max_length=500) class Meta: managed = True db_table = 'userdetails' class signups(models.Model): sname = models.CharField(max_length=20) semail = models.EmailField() spassword = models.CharField(max_length=20) scpassword = models.CharField(max_length=20) class Meta: managed = True db_table = 'logindb' **views.py** from django.http import HttpResponse from django.shortcuts import render from .models import user_details, signups def index(request): context = {"home_page": "active"} # used to make template active when clicked on it return render(request, 'index.html', context) def about(request): context = {"about_page": "active"} return render(request, 'about.html', context) def contact(request): context = {"contact_page": "active"} if request.method == "POST": name = request.POST.get('name', '') email = request.POST.get('email', '') mobile = request.POST.get('mobile', '') category = request.POST.get('category', '') member = True if request.POST.get('member') … -
Docker pulled image inside Gitlab CI/CD doesn't recognise django tests
Title says for itself. Everything works perfectly, except tests. After pulling and running test(test stage) service, it says Ran 0 tests in 0.000s, but i have some basic tests and they run perfectly on my system. Just can't quite figure out what is wrong. I have a docker-compose file like this: version: '2' services: postgres: image: "postgres" ports: - 5432:5432 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=solo - POSTGRES_DB=solo - POSTGRES_PASSWORD=solo - POSTGRES_HOST_AUTH_METHOD=trust web: image: $CI_REGISTRY:$CI_COMMIT_REF_NAME build: . environment: - SECRET_KEY command: bash -c "cd src && gunicorn solo.wsgi:application --bind 0.0.0.0:8000" volumes: - static:/app/static expose: - 8000 depends_on: - postgres restart: always test: image: $CI_REGISTRY:$CI_COMMIT_REF_NAME command: bash -c "python /app/src/manage.py test" depends_on: - postgres nginx: build: ./nginx volumes: - static:/app/static ports: - 80:80 depends_on: - web volumes: static: postgres_data: And .gitlab-ci.yml like this: image: docker:latest services: - docker:dind stages: - build - test - deploy before_script: - apk add --no-cache py-pip - pip install docker-compose==1.9.0 - docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN $CI_REGISTRY build: stage: build script: - docker-compose build - docker-compose push test: stage: test script: - docker-compose pull test - docker-compose run test deploy: stage: deploy only: - master - cicddev before_script: - apk add --update alpine-sdk - apk … -
Passing instances in django - Python
I was wondering how one would pass an instance of an initialized class inbetween apps of django. My Problem is that I start a background thread with a socket handling class in the urls.py file but then I need to use it later in other files to communicate. Something like context in android and java would be handy. Does anybody know an easy fix? Thanks already -
No Django/Flask connections on devices on local network
Before you rush to mark this question as duplicate I have literally looked through every thread and forum and website for answers, all of which don't work. No matter if I use flask or django, I wont be able to connect to the server from a different device (on the same network). I've changed the ports around and ran a few commands in cmd and saw that my computer was infact listening for connections. I have been able to connect only a couple of times, but then immediately after that I am unable to connect. I've been trying to get this working for about 6 hours, and in all that time I have only had two successful connections. Someone please help! (Thanks <3) -
Can not load CSS in Django
I'm new to Django and now I have problem with loading css files. I have this directory tree in my windows system: case 1: . |__myproject |__+myproject |__+myapp |___-static | |___-css | |__style.css |__-templates |__base.html base.html => {% load static %} <!DOCTYPE html> <html> <head> <link href="{% static "css/style.css" %}" rel="stylesheet"> </head> <body> </body> </html> settings.py => BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, "templates") STATICFILES_DIR = os.path.join(BASE_DIR, "static") STATIC_URL = '/static/' STATICFILES_DIRS = [ STATICFILES_DIR, ] INSTALLED_APPS = [ # ... 'django.contrib.staticfiles', # ... ] TEMPLATES = [ { # ... 'DIRS': [TEMPLATE_DIR,], # ... }, ] with those settings and configurations, CSS file can not be loaded. But when I change my directory tree to this: case 2: . |__+myproject |__+myapp |___-static | |__style.css |__-templates |__base.html and base.html => # ... <link href="{% static "style.css" %}" rel="stylesheet"> # ... Now it is working. So what is the problem with case 1? What is missing here? -
Two different - django.db.utils.DataErrors
I'm currently trying to deploy my project, which involves switching form SQLite to PosgreSQL instead, but everytime I change the Database URL & migrate, I get this error. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/workspace/.pip-modules/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 231, in handle post_migrate_state = executor.migrate( File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/migrations/operations/fields.py", line 249, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/backends/base/schema.py", line 564, in alter_field self._alter_field(model, old_field, new_field, old_type, new_type, File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/backends/postgresql/schema.py", line 152, in _alter_field super()._alter_field( File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/backends/base/schema.py", line 719, in _alter_field self.execute( File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/backends/base/schema.py", line 142, in execute cursor.execute(sql, params) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/backends/utils.py", line 100, in execute return super().execute(sql, params) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/backends/utils.py", line 68, in execute … -
Django query not producing desired results
My model is as below: class Person(models.Model): first_name = models.CharField('Name', max_length=200) family_name = models.ForeignKey(Family, on_delete=models.PROTECT) gender_is_male = models.BooleanField(default=True) year_of_birth = models.PositiveIntegerField(null=True, blank=True, validators=[MaxValueValidator(datetime.date.today().year), MinValueValidator(1800)]) month_of_birth = models.PositiveIntegerField(null=True, blank=True, validators=[MaxValueValidator(12), MinValueValidator(1)]) date_of_birth = models.PositiveIntegerField(null=True, blank=True, validators=[MaxValueValidator(31), MinValueValidator(1)]) birth_date = models.DateField(null=True, blank=True) #gregorian_date died = models.BooleanField(default=False) Person object can have either full birth_date or any part thereof in year_of_birth, month_of_birth and date_of_birth. I am trying to get the list of living persons having either full birth_date or year_of_birth, arranged from the oldest to youngest: I tried the following query: oldest_living_list = Person.objects.filter(Q(died=False) &(Q(year_of_birth__isnull=False)|Q(birth_date__year__isnull=False))) .annotate(sort_order=Case( When(birth_date__isnull=False, then=('birth_date__year')), default=('year_of_birth'), output_field=PositiveIntegerField())) .order_by('sort_order') The output first lists all persons according to descending year_of_birth, and then descending birth_date_year, which is not what I want. I cannot understand where I am going wrong. Can someone kindly help? Thanks in advance -
Celery & Django: Scheduling emails to users, passing pk of the object to funciton inside CBV
I am working on a simple Django TODO list project, and I want the user to receive an email notification about a task created and when the due-date of that task is coming (I'm thinking of doing that by passing task_pk to a @shared_task celery function). I have a CreateView that shows a form to create the task, saves it and redirects to the homepage. I want to know a way to pass in the pk (id) of the object created to a function that will then send the email notification to the user of the task. class TaskCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = Task fields = ['title', 'duedate', 'note', 'public'] success_message = f"Task \"%(title)s\" created successfully" # task_created_notification_mail(task.pk) # task_duedate_notification_mail.apply_async((task.pk), eta=task.duedate) def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) The problem I face is that I don't know a way to get the pk of the task after it is created. Here is my tasks.py: @shared_task def task_duedate_notification_mail(task_pk): t = Task.objects.get(pk=task_pk) send_mail(f'TODO tracker: your task "{t.title}" due date is coming up!', 'Hello, please check the task and mark it \"completed\" or \"canceled\"', 'todo.tracker.dev@gmail.com', [t.user.email]) return None @shared_task def task_created_notification_mail(task_pk): t = Task.objects.get(pk=task_pk) send_mail(f'TODO tracker: you have just created a task … -
Heroku "Cannot run more than 1 Free size dynos" for every console command
I'm trying to run a Django application on Heroku. After launching it, next logical step is to make migrations, migrate and create a superuser. But Whenever I try to run these commands, Heroku responds with "Cannot run more than 1 Free size dynos". This is my original Procfile: web: gunicorn UniChat.wsgi I've tried restarting the machine, stopping dyno with these commands: heroku ps:stop -a uni-chat-2, heroku ps:restart. None of that helps. One SO answer suggests using commands in Procfile, so I've modified it to look like this: release: python manage.py makemigrations release: python manage.py migrate web: gunicorn UniChat.wsgi That seems to have solved the problem with regular commands that should be run on every code update but I still cannot make a new superuser.