Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Increase Django CSRF tocken longevity
I get lots of Django CSRF errors due to timeout. In normal operations, the form submissions are OK. But, if I leave the page for a few hours and then submit it, it will fails with the Forbidden (403) CSRF verification failed. Request aborted screen. To overcome this issue, I added the following line to the settings.py : SESSION_COOKIE_AGE = 604800 # one week But a few hours leading to timeout means that this line has had no effect. I need CSRF tokens longevity be increased to a few days rather than minutes. How to achieve this? -
Celery beat_scheduler's task executed but not registered in model django_celery_beat_periodictask
I am trying basic implementation of celery worker and celery beat on the windows PC. The celery beat is sending the task successfully and the celery worker received the task from celery beat and executed the task. The problem is there is no task registered in django_celery_beat_periodictask as expected. Problem: Why there are no task in django_celery_beat_periodictask? Addon questions: If there are no task in django_celery_beat_periodictask then how does the celery beat executing the task? What are the another data sources where celery worker took the task? Project Tree celery_with_django |- django_celery_project |- __init__.py |- settings.py |- celery.py other files |- mainapp |- tasks.py other files |- requirements.txt Command to run the code django server: python manage.py runserver celery worker: celery -A django_celery_project.celery worker --pool=solo -l info **# (without --pool=solo the terminal is hard to interrupt) celery beat: celery -A django_celery_project beat -l info My code look like this requirements.py amqp==5.1.1 asgiref==3.7.2 async-timeout==4.0.2 billiard==3.6.4.0 celery==5.2.7 click==8.1.3 click-didyoumean==0.3.0 click-plugins==1.1.1 click-repl==0.2.0 colorama==0.4.6 cron-descriptor==1.4.0 Django==4.2.1 django-celery-beat==2.5.0 django-celery-results==2.5.1 django-timezone-field==5.1 kombu==5.2.4 prompt-toolkit==3.0.38 python-crontab==2.7.1 python-dateutil==2.8.2 pytz==2023.3 redis==4.5.5 six==1.16.0 sqlparse==0.4.4 typing_extensions==4.6.3 tzdata==2023.3 vine==5.0.0 wcwidth==0.2.6 django_celery_project/init.py from .celery import app as celery_app __all__ = ('celery_app',) django_celery_project/settings.py **# other settings **# CELERY SETTINGS CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_RESULT_BACKEND = 'django-db' … -
Django Celery running a function multiple times?
In Django, I have created an app for sending emails to clients. I am using Celery Beat to schedule a daily task that executes the schedule_emails function at 12:30 AM. This function runs perfectly. However, I am encountering a problem where the send_email function is running multiple times and sending duplicate emails to specific clients from my email account at the same time. I have checked the logs of the celery worker it shows that a particular task_id was received multiple times and succeed succeeded multiple times. I am using the supervisor to run celery and celery_beat services in the background. settings.py # Celery Settings CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' CELERY_TASK_ACKS_LATE = True CELERY_RESULT_BACKEND = 'django-db' CELERY_BEAT_SCHEDULE_FILENAME = '.celery/beat-schedule' CELERYD_LOG_FILE = '.celery/celery.log' CELERYBEAT_LOG_FILE = '.celery/celerybeat.log' CELERY_BEAT_SCHEDULE = { 'schedule_emails': { 'task': 'myapp.tasks.schedule_emails', 'schedule': crontab(hour=0, minute=30), }, } celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings from decouple import config if config('ENVIRONMENT') == 'development': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyProject.settings.development') else: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyProject.settings.production') app = Celery('MyProject**strong text**') app.conf.enable_utc = False app.conf.update(timezone='Asia/Kolkata') app.config_from_object(settings, namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request : {self.request!r}') task.py from celery import shared_task @shared_task def … -
Is it possible to use functions like gettext() inside Formatted String Literals (F-Strings)
So, is it possible to call a function inside Formatted String Literals (F-String) ? ex: from django.utils.translation import gettext_lazy as _ def func(x): return f'{_("Value")}: {x}' print(func(4)) -
Django Q: build dynamic query from array
For a Django project, I have a dictionary which contains the model name and the columns where to look for. So what I want to achieve is to build the query from the variables coming from my dictionary. sq = [] for x in columns: print(x) sq.append(f'Q({x}__icontains=val)') print(sq) query = (' | '.join(sq)) print(query) lookups = Q(name__icontains=val) | Q(code__icontains=val) # lookups = query When I do the above, it correctly builds the "string" representing the query, but I'm unable to use it. The error is as follows: Traceback (most recent call last): File "/home/user/price_engine/env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/user/price_engine/env/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/price_engine/masterdata/views.py", line 50, in search_form results = Plant.objects.filter(query).distinct() File "/home/user/price_engine/env/lib/python3.9/site-packages/django/db/models/manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/user/price_engine/env/lib/python3.9/site-packages/django/db/models/query.py", line 1436, in filter return self._filter_or_exclude(False, args, kwargs) File "/home/user/price_engine/env/lib/python3.9/site-packages/django/db/models/query.py", line 1454, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "/home/user/price_engine/env/lib/python3.9/site-packages/django/db/models/query.py", line 1461, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "/home/user/price_engine/env/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1534, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/home/user/price_engine/env/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1565, in _add_q child_clause, needed_inner = self.build_filter( File "/home/user/price_engine/env/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1412, in build_filter arg, value = filter_expr ValueError: too many values to unpack (expected 2) [05/Jul/2023 04:27:27] "POST … -
How to use a background task but i want it to send it using render to specific url
I try to render but it should put request using parameter, how to handle the request when using the background task in django @background(schedule=60) # Runs every 60 seconds def auto_check_status (request): current_time = timezone.now() time_threshold = current_time - timedelta(minutes=10) try: transactions = Transaction.objects.filter( Q(trx_status='PENDING') | Q(trx_status='SUBMITTED'), trx_type_id='R', trx_time__lt=time_threshold ).order_by('trx_time') for transaction in transactions: # Perform actions on each transaction store_database(transaction) message = createrequest(transaction) message = construct_source_string_and_sign(message) npg_url = f"{settings.NPG_URL}/in" npg_url = f"{settings.NPG_URL}/in" return render(request, 'transactions/bayar.html', {'trx': message, 'npg_url' :npg_url}) except Exception as e: print(str(e)) -
Arabic translations not displayed correctly in Django/Celery notification system
I'm currently working on a Django application that includes various functionalities, including notification delivery, in multiple languages. While most of the application works well with Arabic and other languages, I'm facing an issue with Arabic translations in certain parts of the application, including notifications. The Arabic translations are not being displayed correctly, while translations in other languages, such as English and French, work without any issues. Here are the details of my setup: The application uses Django and Celery for task management and background processing. I have added Arabic translations for different text elements in the respective translation files. The Arabic translations work fine in most parts of the application, including UI labels and content. However, when it comes to notifications, specifically in Arabic, the translations are not displayed correctly. Other functionalities, such as database operations, user management, and data processing, work as expected with the Arabic translations. I have ensured that the necessary translations are present, and the language preferences are correctly set for affected users. The issue seems to be specific to the notification tasks triggered by certain actions or events. It's puzzling because the Arabic translations work well in other areas of the application. I would greatly … -
How to connect 2 views in the same Django app? (ListView and EditView)
I have 2 apps called Prospecto(which means Prospect) and Cliente(which means Customer). When you see a register in EditView and click on its checkbox, you can indicate whether the register is still in Prospecto or Cliente If you don't click on the checkbox, that record is still in the Propsecto If you click the checkbox, that record becomes a Cliente and is no longer a Prospect In the code I did, when I clicked the checkbox, it turns into record in Customer(that's ok), but I can't delete it from Prospecto(in ProspectoListView). **views.py class ProspectoListView(ListView): model = Prospecto template_name = 'prospectos.html' context_object_name = 'prospectos' def get_queryset(self): queryset = super().get_queryset() fecha_inicio = self.request.GET.get('fecha_inicio') fecha_fin = self.request.GET.get('fecha_fin') if fecha_inicio and fecha_fin: queryset = queryset.filter(fecha__range=[fecha_inicio, fecha_fin]) elif fecha_inicio: queryset = queryset.filter(fecha__gte=fecha_inicio) elif fecha_fin: queryset = queryset.filter(fecha__lte=fecha_fin) return queryset def ProspectoEditar(request, pk): prospecto = get_object_or_404(Prospecto, pk=pk) if request.method == 'POST': form = ProspectoForm(request.POST, instance=prospecto) if 'es_cliente' in request.POST: cliente = Cliente(nombre=prospecto.nombre) cliente.save() prospecto.es_cliente = True prospecto.delete() if form.is_valid(): form.save() return redirect('prospectos:prospectos_list') else: form = ProspectoForm(instance=prospecto) return render(request, 'prospectos-editar.html', {'form': form}) I try with this solution, adding delete() but it doesn't work class ProspectoListView(ListView): model = Prospecto template_name = 'prospectos.html' context_object_name = 'prospectos' def get_queryset(self): fecha_inicio … -
Failed to join room. Token authentication error
I am working on a django project in which I have used zeegocloud uikits for one-one video calling web application. Even when I am using the downloadable uikits html file provided by zeegocloud itself, in which it has generated token using appID, userID, serversecret, username, but then also token authentication error is coming. I am unable to solve this issue -
Docker Compose Up - Received Permission Denied
I am unable to start a new django/python app with docker. I received permission denied. I recently bought a new computer and my app I had previously used with docker is working fine. I then recently tried to build a flask/carmen app but deleted everything that I had loaded. Im not sure if that is effecting my docker containers but my previous app will still do docker compose up and down. I tried this weekly-finances docker-compose config name: weekly-finances services: web: build: context: /Users/eleahburman/Desktop/code/weekly-finances dockerfile: Dockerfile command: - python - manage.py - runserver - 0.0.0.0:3000 networks: default: null ports: - mode: ingress target: 3000 published: "3000" protocol: tcp volumes: - type: bind source: /Users/eleahburman/Desktop/code/weekly-finances target: /code bind: create_host_path: true networks: default: name: weekly-finances_default and the docker compose seems correct. Here is my yaml file: services: web: build: . command: python manage.py runserver 0.0.0.0:3000 volumes: - .:/code ports: - "3000:3000" and here is my docker file: syntax=docker/dockerfile:1 FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ I tried deleting every app I had by docker and then cloning and adding an env. I started over my new app. I tried deleting … -
I have no clue what's going on
I just got to finishing a tutorial with the following link: https://www.youtube.com/watch?v=eOVLhM6_6t0&t=572s and the last step is to check that the server is running properly using python manage.py runserver however when I try to do this, the usual error pops up: [Errno 2] No such file or directory which I was able to solve with the absoulte path solutions provided online. However my problem is not that the problem comes when I finally reach the right cd to be in and all of this errors appear in the terminal: https://docs.google.com/document/d/1PJB2rRQ-Lyd8GQd3Hl9krkTlHD9C60WeakNk-9tM5y0/edit It was so long I couldn't even copy it all here without the computer bugging I have no clue what even is going on here or how could I solve it. I've been stuck here for the past hour. Thanks for the help. -
404 Not Found nginx/1.18.0 (Ubuntu) on running django rest framework with EC2 along with gunicorn, nginx and Supervisor
So I hosted my django rest framework project on AWS EC2. I integrated nginx, gunicorn and Supervisor along with it. After it shows successful configuration, the only link that works is the default one. Example http://35.154.109.114/ works but any other URL say http://35.154.109.114/test isn't working How ever these links work when I use a standard gunicorn --bind 0.0.0.0:8000 DemoProject.wsgi:application command. Please let me know how to work this out. -
Django passing a string from one view to another
I have one view with a chatbot on it, and it works fine. I added a second view and registered it in the urls.py file and simply passed the chatbot response to the new function to display and I got a 500 error. The code from my views.py, urls.py, main.html, and main_2.html pages is posted below. What am I missing? Thanks in advance. VIEWS.PY ` from django.shortcuts import render import openai, os from dotenv import load_dotenv from django.http import HttpResponse load_dotenv() api_key = os.getenv("OPENAI_KEY", None) def chatbot(request): chatbot_response = None if api_key is not None and request.method == 'POST': openai.api_key = api_key user_input = request.POST.get('user_input') prompt = user_input response = openai.Completion.create( engine = 'text-davinci-003', prompt = prompt, max_tokens=256, # stop="." temperature=0.5 ) print(response) chatbot_response = response["choices"][0]["text"] sayhi(request, chatbot_response) <-----(The error comes from this line. When I comment this out it works fine return render(request, 'main.html',{"response": chatbot_response}) def sayhi(request, chat_out): #return HttpResponse("hi") return render(request, 'main_2.html',{"response": chat_out}) URLS.PY (located in the parent directory of the views.py file) urlpatterns = [ path("", chatbot, name="chatbot"), # Uncomment this and the entry in `INSTALLED_APPS` if you wish to use the Django admin feature: # https://docs.djangoproject.com/en/4.2/ref/contrib/admin/ # path("admin/", admin.site.urls), path("sayhi", sayhi) ] MAIN.HTML {% extends 'base.html' … -
Link from Django Model's "absolute url" to its admin page
According to the docs, you can specify a get_absolute_url in your Django Model for a "View on site" button to show up on Django Admin. However, how would you do the opposite? A link on the above defined "absolute url" that takes you to the admin page for that instance? I can think of ways to hardcode the admin url and fill in just the instance ID, but I was hoping for a pythonic way (e.g. instance.get_admin_url()) Thanks for the help! -
I am Trying to create my first Django Project on VS Code and I cant figure out how properly install the packages needed
I am a begginer programmer who was trying to create his first project in VS Code. I installed in the Windows Powershell Django and activated a virtual environment as followed through the following pages: https://docs.djangoproject.com/en/4.2/howto/windows/ And also tried to install it on VS Code directly following this tutorial on YT: https://www.youtube.com/watch?v=Wfu5dPbiyKA however the following problems occur when I check the files in VS Code wsgi.py: from django.core.wsgi import get_wsgi_application This line throws the following warning: Import "django.core.wsgi" could not be resolved from source and the same error is thrown in the urls.py file and asgi.py file for the following: Asgi: from django.core.asgi import get_asgi_application Urls: from django.contrib import admin from django.urls import path After some research I discovered that either I installed incorrectly Django into my computer or VS Code or either I can install them individually, however neither have worked as when I try to check the status of django it says that the module doesnt exist. Please help, thanks -
Celery does not find models when performing the task
I'm writing an Api for a telephone newsletter, my code accepts dispatch requests and when it's time to start the newsletter it sends a request to an external Api, which in turn sends the messages themselves. If you run everything outside of docker, it works fine, but when you run it in docker-compose, the src.newsletter.models.Dispatch.DoesNotExist: Dispatch matching query does not exist. I'm pretty sure models with this index exist, but celery gives the error tasks.py from celery import shared_task from src.newsletter.models import Dispatch, Client, Message from config.settings.development import API_SENDING_URL, API_JWT_TOKEN import requests @shared_task def send_message_to_client(dispatch_id, client_id): dispatch = Dispatch.objects.get(id=dispatch_id) client = Client.objects.get(id=client_id) url = f"{API_SENDING_URL}{client.id}" headers = {"Authorization": f"{API_JWT_TOKEN}"} data = { "id": client.id, "phone": client.phone_number, "text": dispatch.text_message, } try: response = requests.post(url, headers=headers, json=data) print(response.status_code) if response.status_code == 200: message = Message.objects.create( status='S', dispatch=dispatch, client=client ) elif response.status_code == 401: message = Message.objects.create( status='F', dispatch=dispatch, client=client ) elif response.status_code == 400 or response.elapsed.total_seconds() > 10: # Повторная попытка отправки try: response_retry = requests.post(url, headers=headers, json=data) if response_retry.status_code == 200: message = Message.objects.create( status='S', dispatch=dispatch, client=client ) else: message = Message.objects.create( status='F', dispatch=dispatch, client=client ) except requests.exceptions.RequestException: message = Message.objects.create( status='F', dispatch=dispatch, client=client ) else: message = Message.objects.create( status='F', dispatch=dispatch, … -
Django Redirecting to custom prefilled form
So I have the following issue regarding a custom project. I made a page with different pets which are ready for adoption. Each one has a button for Details. I want when a user is Logged In to see a button which indicates that saying "Adopt". When the button is pressed I want to redirect him to a new page with some prefilled fields from the Pet model (the pet which is ready for adoption) and I want the user to fill few new fields. When he press another button (Send...etc.) to tell him that the request is send out. I tried and see that the pk of the first ready for adoption animal is 1, but when I go the url it is saying that no URL is found. Here are some of my code. urls.py urlpatterns = [ path('adoption/create/', AnimalAdoptCreateView.as_view(), name='animal_adopt_create'), path('adoption/', AnimalAdoptListView.as_view(), name='adoption_animals'), path('adoption/details/<int:pk>', AnimalAdoptDetails.as_view(), name='adoption_animals_details'), path('adoption/details/<int:pk>/adopt/', AnimalAdoptFormSendView.as_view(), name='adopt_form'), ] views.py class AnimalAdoptDetails(LoginRequiredMixin, DetailView): model = AnimalAdoptReadyCreate template_name = 'animal_adopt_detail.html' class AnimalAdoptFormSendView(LoginRequiredMixin, UpdateView): model = AnimalAdoptSend form_class = AnimalAdoptSendForm template_name = 'animal_adopt_form.html' models.py class AnimalAdoptReadyCreate(models.Model): animal_choice = { ('dog', 'Dog'), ('cat', 'Cat'), ('other', 'Other') } animal_name = models.CharField(max_length=20) animal_type = models.CharField(max_length=30, choices=animal_choice) location = models.CharField(max_length=60) details = … -
https forced in development by django. Problem with DJANGO_SECURE_HSTS_SECONDS?
Something in my Django code is forcing development server (runserver) redirection from http to https. I get these logs by docker web container after running docker compose up -d --build and trying to access my website development server: 2023-07-04 10:16:50 Starting development server at http://0.0.0.0:8000/ 2023-07-04 10:16:50 Quit the server with CONTROL-C. 2023-07-04 10:16:49 Watching for file changes with StatReloader 2023-07-04 10:18:03 [04/Jul/2023 08:18:03] "GET / HTTP/1.1" 301 0 2023-07-04 10:18:03 [04/Jul/2023 08:18:03] code 400, message Bad request version ('YñEë\x99õUÂ~Ô¾OÝ6P+') 2023-07-04 10:18:03 [04/Jul/2023 08:18:03] You're accessing the development server over HTTPS, but it only supports HTTP. These are my django security settings in: SECURE_SSL_REDIRECT = os.environ.get("DJANGO_SECURE_SSL_REDIRECT", default=True) SECURE_HSTS_SECONDS = int(os.environ.get("DJANGO_SECURE_HSTS_SECONDS", default=2592000)) SECURE_HSTS_INCLUDE_SUBDOMAINS = os.environ.get("DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True) SECURE_HSTS_PRELOAD = os.environ.get("DJANGO_SECURE_HSTS_PRELOAD", default=True) SESSION_COOKIE_SECURE = os.environ.get("DJANGO_SESSION_COOKIE_SECURE", default=True) CSRF_COOKIE_SECURE = os.environ.get("DJANGO_CSRF_COOKIE_SECURE", default=True) But i changed them to make them False in development with environment variables in .env file: DJANGO_DEBUG=1 DJANGO_SECURE_SSL_REDIRECT=False DJANGO_SECURE_HSTS_SECONDS=0 DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS=False DJANGO_SECURE_HSTS_PRELOAD=False DJANGO_SESSION_COOKIE_SECURE=False DJANGO_CSRF_COOKIE_SECURE=False But actually these seem ok and I got the same problem, https is forced. Please what could cause the forcing of redirecting from http to https? I tried changing browser (chrome and firefox), changing env variables, deleting browser cache and basically everything I found on the internet but nothing changes … -
I want to design a shipping option, for standard and express in django
forms.py SHIPPING_CHOICES = ( ('S', 'Standard'), ('E', 'Express'), ) class Shipping(forms.Form): shipping_option = forms.ChoiceField(widget=forms.RadioSelect, choices=SHIPPING_CHOICES) views.py class OrderSummaryView(LoginRequiredMixin, View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) form = Shipping() context = { 'form' : form, 'object' : order, 'couponform': CouponForm(), 'DISPLAY_COUPON_FORM': True, } return render(self.request, 'cart.html', context) except ObjectDoesNotExist: messages.info(self.request, "You do not have an active order") return redirect('estores:home') def post(self, *args, **kwargs): form = Shipping(self.request.POST) order = Order.objects.get(user=self.request.user, ordered=False) if form.is_valid: shipping_option = form.cleaned_data.get('shipping_option') if shipping_option == 'S': order.options ='Standard' order.save() elif shipping_option == 'E': order.options = 'Express' order.save() html <form method="POST"> {% for value, name in form.fields.shipping_option.choices %} <tr class="summary-shipping-row"> <td> <div class="custom-control custom-radio"> <input id="{{ name }}" type="radio" name="shipping_option" value="{{ value }}" class="custom-control-input" required> <label class="custom-control-label" for="{{ name }}">{{ name }}</label> </div> </td> </tr> {% endfor %} </form> I want to retrieve the value of the form option and save it to my order shipping option. anytime i am on the cart page, there should be two options for shipping. either standard or express and i want to be able to add the shipping prices to the order price. -
Page not found (404) error message when using get_object_or_404 method
thank you so much for your help. this is the error message i get when running the code. Page not found (404) *Request Method: GET * Request URL: http://127.0.0.1:8000/blog/1/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ blog/ [name='post_list'] blog/ <int:year>/<int:month>/<int:day>/<slug:post>/ [name='post_detail'] The current path, blog/1/, didn’t match any of these. views.py in blog directory def post_detail(request,year,month,day,post): post = get_object_or_404(Post, status=Post.Status.PUBLISHED, slug=post, publish__year=year, publish__month=month, publish__day=day ) return render(request, 'blog/post/detail.html', {"post":post}) models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class Post(models.Model): class Status(models.TextChoices): DRAFT='DF', 'Draft' PUBLISHED = 'PB', 'Published' title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=2, choices=Status.choices, default=Status.DRAFT) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blog_posts") def __str__(self): return self.title class Meta: ordering = ['-publish'] indexes = [models.Index(fields=['-publish'])] def get_absolute_url(self): return reverse("blog:post_detail", args = [self.publish.year, self.publish.month, self.publish.day, self.slug]) urls.py in mysite.urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls', namespace='blog')) ] urls in blog directory from django.urls import path from . import views app_name='blog' urlpatterns = [ path('', views.PostListView.as_view(),name='post_list'), path('<int:year>/<int:month>/<int:day>/<slug:post>/', … -
Django: aggregate django fields to avoid N + 1 problem
I have 3 tables/classes that are relevant to each other: CourseStudent - represents Student signed up to the course Presence - represents the attendance list of the CourseStudent CourseStudentPayment - represents the payments list for CourseStudent In the code it looks like this: class CourseStudentPayment(models.Model): course_student = models.ForeignKey( "CourseStudent", on_delete=models.CASCADE, related_name="course_student_payments", ) start_date = models.DateField(db_index=True) # other fields: price, currency, etc price = models.DecimalField(default=0, max_digits=10, decimal_places=2) def lessons_complete(self) -> int: return ( Presence.objects.filter( course_student=self.course_student, ) .filter(date__gte=self.start_date) .count() ) class Presence(models.Model): course_student = models.ForeignKey("CourseStudent", on_delete=models.CASCADE) date = models.DateField() # some other fields class CourseStudent(models.Model): # some course-related information student = models.CharField(...) def last_payment(self) -> CourseStudentPayment: return CourseStudentPayment.objects.filter(course_student=self).order_by("-start_date").first() So lessons_complete function calculates the number of the attendances since the payment date. Both CourseStudentPayment and Presence objects have CourseStudent pk. I want to render a list of payments for the students with lessons_complete in an efficient way. The dumb solution would be: get list of payments. course_payments = CourseStudentPayment.objects.all() for each payment I call lessons_complete. This solution creates N+1 problem, where for each payment I do Presence lookup. In SQL I would just join two tables (pseudocode): SELECT csp.*, count(p.id) from CourseStudentPayment csp JOIN Presence p ON scp.course_student_id = p.course_student_id WHERE p.date > … -
Why it can't pass a validation with the django form when set data after initializing
Why it can't pass a validation when I set data like this (form.data=request.POST) @login_required def add_delivery_view(request): user = request.user delivery = (Delivery.objects.filter(user=user) or [None])[0] form = AddDeliveryForm(instance=delivery) if request.method == 'POST': form.data = request.POST if form.is_valid(): delivery = form.save(commit=False) delivery.user = request.user form.save() return redirect('/') return render(request, 'order/add_delivery.html', {'form':form}) But when I set data like this, it works just fine ... if request.method == 'POST': form = AddDeliveryForm(data=request.POST, instance=delivery) if form.is_valid(): delivery = form.save(commit=False) ... I guess it something with initialization of form. Maybe I should add some method after form.data=request.POST Question is: What is the difference underneath the hood? Thanks in advance -
response.set_cookie() vs response.cookies[] in Django
I could set the cookies with response.set_cookie() and response.cookies[] as shown below: # "my_app1/views.py" from django.http import HttpResponse def test(request): response = HttpResponse('Test') response.set_cookie('first_name', 'John') # Here response.cookies['last_name'] = 'Smith' # Here return response Then, I could only delete response.set_cookie()'s cookie first_name rather than response.cookies[]'s cookie last_name with response.delete_cookie() as shown below: # "my_app1/views.py" from django.http import HttpResponse def test(request): response = HttpResponse('Test') response.delete_cookie('first_name') # Deleted response.delete_cookie('last_name') # Undeleted return response So, what is the difference between response.set_cookie() and response.cookies[] in Django? -
Django - Model - Is it possible to use dict key value in UniqueConstraint combined with other attributes
Short version of the question: Is it possible to use dict key value in UniqueConstraint. If not, advice on implementing the logic described; *I use postgreSql In django, I have a model which; has a name attribute which is an I18nCharField meaning, on the form, for the name attribute there are two inputs, one for english and one for portuguese. Other attributes are like below. Unique Constraints: (second one is the problem here) Acronym and Code can be null. This is why I have these UniqueConstraints with query in here. But the involvement of the name should be based on only the portuguese version. English one can be even blank. (name is mandatory but only the portuguese one) What my problem is; this name field is being saved as: {"en": "record5-level3", "pt": "registro5-nível3"} meaning, I cannot use this in the Unique Constraints as it is because someone can just use the same portuguese name and put random stuff in the english input. I cannot keep uniqueness on the pt name with other attributes. What I want to do is; customize this unique constraints in order to consider name as its pt value inside, or use the UniqueConstraints with name.pt Is … -
Simple audio player with <audio> tag not able to control time progress in chrome running on python server (but works on safari and node server)
Very basic audio player, running on python server locally. If I run it on safari, it works fine. If I run it on a node server, it works fine on chrome and safari. But ultimately this will be apart of a django project and needs to run on python server. For some reason on a python server (on chrome only), the audio plays, but I can only stop or go back to beginning. If I click anywhere else on the audio it stays there. There are no errors in console. I do get this in the server log for my entire django project: [04/Jul/2023 12:04:39,230] - Broken pipe from ('127.0.0.1', 61887). I am running python3. Code: <html> <head> <title>Audio Player</title> </head> <body> <h1>Audio Player</h1> <audio controls> <source src="test.mp3" type="audio/mpeg"> Your browser does not support the audio element. </audio> </body> </html>