Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django date() doesn't translate uk and run month names
When I try to get localized datetime in a template using {{ enrolment.datetime_access_ends|date:"j E Y" }} I get 29 July 2025 (instead of expected 29 июля 2025). Localization works fine in all other places. I have this in my settings.py: LOCALE_PATHS = [BASE_DIR / "locale"] # type: ignore TIME_ZONE = "Europe/Kiev" USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGE_CODE = "ru-UA" LANGUAGES = [ ("ru", _("Russian")), ("uk", _("Ukrainian")), ] When I try to get month translation from shell, I get expected results: >>> activate("uk") >>> date(timezone.now(), "F") 'Серпень' >>> activate("ru") >>> date(timezone.now(), "F") 'Август' But when I try to do the same from inside of the view, for some reason it doesn't work: print(get_language()) print(date(timezone.now(), "F")) gives ru August in logs. And if I change language to any other then uk or ru activate("pt") it works fine: pt Agosto -
Django + Javascript - dynamic ModelForm generation issue
I have this code {% extends 'base.html' %} {% block content %} <form method='POST'> <script> function addMemberFnc() { document.getElementById("teamMemberDiv").innerHTML+={{ project_members_form }} } </script> {{ project_form }} <p id="demo" onclick="addMemberFnc()">Add member.</p> <div style="border-style: dotted" id="teamMemberDiv"> {# {{ project_members_form }}#} </div> <button type="submit" class="btn btn-primary my-5">Submit</button> </form> {% endblock %} I would like to add project_member_form based on some action (it does not really matter now what action). This is not working because it seems that JS is not able to see Python variable in <script> block. Here is issue I've got: EDIT: I have got single form without any functions working without any issues. Here is my render method: def project_generation(request): if request.method == 'POST': pass else: project_form = ProjectForm(prefix='Project') project_role_form = ProjectRoleForm(prefix='ProjectRole') project_members_form = ProjectMemberForm(prefix='ProjectMember') # logging.debug(project_form) # logging.debug(project_members_form) return render(request, "project_xml_generation.html", { "project_form": project_form, "project_members_form": project_members_form }, ) -
Django translation html not translating the string when html files are included using include statement
views.py: def process_request(request, data) context = { 'category': datacategory, 'info': data.abc 'language_code': language_code } return TemplateResponse(request, template='.../components/test.html', context=context) test.html: {% load i18n %} {% load static %} <div class=""> <p>{% translate 'hello world' %}</p> {% include 'hash_processor/components/test2.html' %} </div> test2.html: {% load i18n %} {% load static %} <div class=""> <p>{% translate 'hi... world234567' %}</p> {% include 'hash_processor/components/test3.html' %} </div> test3.html: {% load i18n %} {% load static %} <div class=""> <p>{% translate 'heyy world234567' %}</p> </div> django.po: #: templates/hash_processor/components/test.html:6 msgid "hello world" msgstr "hgfghjkl wojehfvejh" #: templates/hash_processor/components/test2.html:6 msgid "hi... world234567" msgstr "hi....fjkherjfger kfhgerhjkf233" #: templates/hash_processor/components/test3.html:6 #, fuzzy #| msgid "hi... world234567" msgid "heyy world234567" msgstr "heyyy...ghewjfgdjhdfr kfhgerhjkf233" output on broswer: string coming for translation in django.po but not rendering in browser till level 2 it is working fine, but at 3 level translated string not showing -
Python Django Form - issue with checkboxes in ModelMultipleChoiceField
I have this model class ProjectMember(models.Model): member_name = models.CharField(max_length=100) member_uid = models.CharField(max_length=15) member_reviewer_uid = models.CharField(max_length=15) member_roles = models.ManyToManyField('ProjectRole', blank=False) member_discipline = models.ManyToManyField('ProjectDiscipline', blank=False) class ProjectRole(models.Model): role_name = models.CharField(max_length=10, unique=True) def __str__(self): return self.role_name this Form class ProjectMemberForm(forms.ModelForm): class Meta: model = ProjectMember fields = ( 'member_name', 'member_uid', 'member_reviewer_uid', 'member_roles' ) # member_roles = forms.ModelChoiceField( member_roles = forms.ModelMultipleChoiceField( queryset=ProjectRole.objects.all(), widget=forms.CheckboxSelectMultiple(attrs={'class': 'form-control'}), required=True, # empty_label=None, # Hide the empty label for the select multiple widget. ) widgets = { 'member_name': forms.TextInput(attrs={'class': 'form-control'}), 'member_uid': forms.TextInput(attrs={'class': 'form-control'}), 'member_reviewer_uid': forms.TextInput(attrs={'class': 'form-control'}), } I have tried also the commented lines of code. I am still getting only this I would call it listbox instead of checkboxes: My issue is that I would like to have it as checkbox instead of this list to crosscheck everything I want to be active. EDIT: Note that I do not intent to save any data into database. This is going to act as configuration server and output is .xml file. -
How do I add custom field in swagger ui in django application?
With every request the api endpoint requires a header name 'VENDOR'. I need to create a field in Django swagger ui to add the VENDOR value and attach it to the headers in every request. I tried customizing swagger settings in Django settings but it didnot work I want something similar like the one in the image but has to be vendor in the field and add to its the request image link -
Unable to display dash-plotly graph in webapp written with django/angular
The company were I work is building a website that is supposed to show some graphs and statistics. The front-end is written in angular and the back-end in python. I would like to use dash to create the plots but I'm having a hard time displaying my test dash app. In the front end there is a button 'draw graph' that when pressed should open a new window with where the app is shown. I tried following the django-plotly-dash tutorial but for some reason I cannot make it work. I'm relatively new to django btw. I have a graph app in the django project. My testing dash app is in dash_app.py and it contains a button that does nothing. from dash import html from django_plotly_dash import DjangoDash app = DjangoDash("Test") app.layout = html.Div([html.Button("Submit", id="submit-value")]) My template is dash_template.html <!DOCTYPE html> <html> <head> <title>Dashboard</title> {%load plotly_dash%} </head> <body> <h1>Dashboard Test</h1> {%plotly_app name="Test" %} </body> </html> And the views.py looks like this. def dash_view(request): return render(request, "graph/dash_template.html") When I click the the draw_graph button, the new window opens and the header Dashboard Test is displayed but the Submit button does not appear. I have already added path("django_plotly_dash/", include("django_plotly_dash.urls")) to the project urls.py … -
Django Email Sending Issue: Email Not Sent and Not Appearing in Sent Items
I'm working on a Django project where I need to send an email with an attached PDF file. My current setup is as follows: Django Version: 4.0.3 Python Version: 3.12.2 Problem: The code runs without throwing any errors. However, the email is not being received by the recipient. The email is also not appearing in the "Sent" folder of the sending Gmail account. Things I've Tried: Verified that the email configuration in settings.py is correct, using the Gmail SMTP server. Checked that the PDF file exists at the specified path. Ensured that there are no exceptions thrown during the email sending process. Tried sending a simple email without attachment, but still no success. Checked Gmail account security settings, including enabling "Less secure app access" and using an App Password. ** Questions: ** What might be causing the email to not be sent or appear in the sent items? Are there any additional debugging steps I can take to figure out what's going wrong? Could there be an issue with Gmail's SMTP server, or is there something I might be missing in the Django configuration? def send_email(request, customer_id): try: order = customer_agent.objects.get(customer_id=customer_id) except customer_agent.DoesNotExist: return HttpResponseNotFound("Order not found") subject = 'Your … -
CSRF issue while calling the api from the frontend [closed]
Create_admin.py def create_agent(request): if request.method == 'POST': name = request.POST.get('name') username = request.POST.get('username') password = request.POST.get('password') if name and username and password: agent = Agent.objects.create(name=name, username=username, password=password) return JsonResponse({'status': 'success'}) return JsonResponse({'status': 'failed'}, status=400) return render(request, 'superadmin/create_agent.html') @user_passes_test(is_super_admin) def fetch_payments(request): if request.method == 'GET': payments = Payment.objects.all().values() # Fetch all payment data return JsonResponse(list(payments), safe=False) class PaymentListView(APIView): def get(self, request): payments = Payment.objects.all() data = [ { "id": payment.id, "agent_name": payment.agent_name, "amount": payment.amount, "payment_link": payment.payment_link, "status": payment.status, "created_at": payment.created_at, } for payment in payments ] return JsonResponse(data, safe=False) create_admin.jsx const handleCreateAgent = async (e) => { e.preventDefault(); const csrfToken = getCSRFToken(); // Get the CSRF token try { const response = await axios.post('http://127.0.0.1:8000/api/superadmin/create-agent/', { username, password, name: agentName, }, { headers: { 'X-CSRFToken': csrfToken, // Include the CSRF token in the headers }, withCredentials: true }); setMessage('Agent created successfully!'); setUsername(''); setPassword(''); setAgentName(''); } catch (error) { console.error('There was an error creating the agent!', error); setMessage('Failed to create agent.'); } }; Forbidden (CSRF cookie not set.): /api/superadmin/create-agent/ [13/Aug/2024 12:32:07] "POST /api/superadmin/create-agent/ HTTP/1.1" 403 2869 This the error that i'm getting when calling the api from the frontend.isssue is that i have already set the cookies thing CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_HTTPONLY = … -
Can't use psycopg3 on Mac?
My Django project currently uses psycopg2. When I try to switch to psycopg3, I get the following error: OSError: cannot load library 'pango-1.0-0' I tried upgrading pip, reinstalling pango, and I also tried starting over with a fresh virtualenv. I still get the same error. I'm using Django 4.2 with Python 3.10 -
Django,There is no module named "myapp"
enter image description here PS C:\Users\taipe\firstproject> & C:/Users/taipe/AppData/Local/Programs/Python/Python312/python.exe c:/Users/taipe/firstproject/firstproject/urls.py Traceback (most recent call last): File "c:\Users\taipe\firstproject\firstproject\urls.py", line 19, in from myapp.views import sayhello,sayhello2,hello3 ModuleNotFoundError: No module named 'myapp' PS C:\Users\taipe\firstproject> enter image description here I don`t know why there is the problem of "no module named "myapp" ". however, there actually is a "myapp" folder in my "firstproject". -
Django generic DetailView: what is the best way to optionally include a reverse-related object?
Background Models Let's say I have a django generic DetailView that I use to display a single object instance of a model called Car. Then let's say I have another model called Race. Among many fields, this Race model has a ForeignKey field that is linked to Car (i.e., the Car that a Driver (user) used for a Race). Example models.py from django.conf import settings class Car(models.Model): """ a bunch of fields, including many fk fields """ class Race(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name="races") driver = models.models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) """ a bunch of other fields, including fk fields """ View Now let's say I have a generic DetailView that my website's users have used for a long time to see a single car object. Example views.py This has a very simplified queryset (my actual queryset has the same sort of structure but more reverse-related fields with their respective related fields). from django.views import generic class CarDetailView(generic.DetailView): model = Car queryset = Car.objects.select_related( """ a bunch of related fields """ ).prefetch_related( """ some reverse related fields """, Prefetch(""" a reverse related field """, SomeReverseRelatedField.objects.select_related(""" some of its related fields """)), ) New feature :) Recently, however, I've implemented a way for my … -
Django: how do I make a dependent dropdown load a filtered list of objects on the update form?
I have multiple dependent dropdowns throughout my application. To add a new record, the form works as expected; for example, you select a Country and the list of State objects for that Country will load, you then select a State and the Suburb objects for that State will load. You save the record, it has all the fields saved correctly, you view the record and all the info can be viewed all as expected. The problem I have is when I want to change/update the record. The instantiated SuburbForm is told to first load a blank dropdown for State, and call a function load_dropdowns when the parent object Country has been set. This action of calling load_dropdowns does not seem to happen in the update form, instead it just stays blank, even if I try to re-select the parent. If I change the instantiated form to load all objects instead of the blank dropdown, the update form fills in the field correctly, but that means the add new and update forms now load all objects instead of the filtered list. models.py from django.db import models class Country(models.Model): item_name = models.CharField(verbose_name="Country") class State(models.Model): item_name = models.CharField(verbose_name="State") state_in_country = models.ForeignKey(Country, on_delete=models.SET_NULL, verbose_name="Country", … -
How to concatenate in Dango annotate()
I want to concatenate a string variable with one of my field, but can't figure out what I'm doing wrong I tried this, where prefix is a string and filename_mask is a field in the table plots = ( PlotDefinitions.objects.filter(is_active=True) .annotate( filename=Concat(Value(prefix), 'filename_mask') ) .values('name', 'description', 'filename') ) I get the error Expression contains mixed types: CharField, TextField. You must set output_field. even though I'm concatenating 2 String type. So I added output_field plots = ( PlotDefinitions.objects.filter(is_active=True) .annotate( filename=Concat(Value(prefix), 'filename_mask', output_field=CharField()) ) .values('name', 'description', 'filename') ) but this gives me the error "'CharField' object has no attribute 'get_internal_type'" -
Nested Serializer with Foreign Key and to_field
Stock model has a OneToMany relationship with Data model. I am using the to_field to link them via model_number field. class Stock(models.Model): model_number = models.CharField(max_length=100, unique=True, null=True) model = models.CharField(max_length=100) brand = models.CharField(max_length=100) msrp = models.IntegerField(default=0) def __str__(self): return f"{self.brand} - {self.model} - {self.model_number}" class Data(models.Model): model_number = models.ForeignKey(Stock, to_field='model_number', on_delete=models.CASCADE) price = models.FloatField() date = models.DateField() def __str__(self): return self.model_number I have my serializers to show each model number and then the nested relationship of data. class DataSerializer(serializers.ModelSerializer): class Meta: model = Data fields = '__all__' class StockSerializer(serializers.ModelSerializer): data = DataSerializer(many=True, read_only=True) class Meta: model = Stock fields = ['brand', 'model', 'model_number', 'msrp', 'data'] However the price does not return at all in my API view. Not sure where I am going wrong on this. -
Django 5 update_or_create reverse one to one field
On Django 4.x Code is working as expected from django.db import models class Project(models.Model): rough_data = models.OneToOneField( "Data", related_name="rough_project", on_delete=models.SET_NULL, null=True, blank=True, ) final_data = models.OneToOneField( "Data", related_name="final_project", on_delete=models.SET_NULL, null=True, blank=True, ) data, created = Data.objects.update_or_create( rough_project=project, defaults=data ) On Django 5.x: ValueError: The following fields do not exist in this model: rough_project I do not see any changes related to this in changelog -
Django- How to retrive ChoiceField value from a form?
I want to get the selected choice from a ChoiceField in a view. When I submit the form, I process it in a view: views.py def myFormSubmitView(request): ... if form.is_valid(): print("valid form") post = Post() post.title = form.cleaned_data["title"] post.body = form.cleaned_data["body"] **>>>>post.choice_test = form.cleaned_data["choice_test"]** post.save() return HttpResponseRedirect(request.path_info) I want to get the value of choice_test. How can I do that ? -
AttributeError: /usr/lib/libgdal.so.20: undefined symbol: OSRSetAxisMappingStrategy
I'm trying to start my project in docker, it was working great, but now something happened and it can't start. It crashes with AttributeError: /usr/lib/libgdal.so.20: undefined symbol: OSRSetAxisMappingStrategy I searched a lot but have no idea how to make it work. I've tried updating all the libs I have, but no effect whatsoever. Here's what I use: Django Postgis Docker-compose Docker My docker configuration: FROM python:3.11-buster # Set work directory WORKDIR /app # Install system dependencies RUN apt-get update \ && apt-get install -y \ binutils \ libproj-dev \ gdal-bin \ libgdal-dev \ postgresql-client \ && rm -rf /var/lib/apt/lists/* \ ENV CPLUS_INCLUDE_PATH=/usr/include/gdal ENV C_INCLUDE_PATH=/usr/include/gdal # Install Poetry COPY pyproject.toml poetry.lock* ./ RUN pip install poetry && \ poetry config virtualenvs.create false && \ poetry install --no-dev # Copy the application code COPY . . # Expose ports EXPOSE 8000 EXPOSE 8001 # Run the application ENTRYPOINT ["sh", "-c", "poetry run gunicorn app.wsgi:application --bind 0.0.0.0:8000"] -
Django complex relation with joins
I have the following models: class Position(BaseModel): name = models.CharField() class Metric(BaseModel): name = models.CharField() class PositionKPI(BaseModel): position = models.ForeignKey(Position) metric = models.ForeignKey(Metric) expectation = models.FloatField() class Employee(BaseModel): position = models.ForeignKey(Position) class EmployeeKPI(BaseModel): employee = models.ForeignKey(Employee) metric = models.ForeignKey(Metric) value = models.FloatField() def kpi(self): return PositionKPI.objects.filter(position=self.employee.position, metric=self.metric).first() I believe it's possible to rewrite the kpi method as a relation. In SQL it would look something like this: select positionkpi.* from employeekpi join employee on employee.id = employeekpi.employee_id join positionkpi on positionkpi.id = employee.position_id and positionkpi.metric_id = employeekpi.metric_id Please advise how to do it -
Huey consumer with Django on Heroku
I am trying to use Huey with Django on Heroko. The Django app starts up as well as the consumer. i can see both logfiles on my dashboard. The Django app runs without problems when a task is enqueued or called the consumer does not register the task and nothing happens. My Procfile starts the consumer with worker: python manage.py run_huey, When I run it locally everything works fine. Any pointers? -
Invalid templates library specified. ImportError raised when trying to load 'django.templates.defaulttags': No module named 'django.templates'
Can anyone help me to solve this problem? when I try to run this django "py manage.py runserver" then I received error "Invalid templates library specified. ImportError raised when trying to load 'django.templates.defaulttags': No module named 'django.templates'" I'm not using templates for this particular project because my team was planning to separate frontend and backend of our app. Anyone can help me or give advise. We're hoping to use other framework other than laravel so I hope our learning journey keeps goin before giving up *hope not Solution or Advice PLEASE -
Django annotation returns 1 for each item
I have 2 almost identical models. class FavoriteBook(models.Model): class Meta: # Model for books added as favorites verbose_name = "Favorite Book" unique_together = ['user', 'book'] user = models.ForeignKey(User, null=False, blank=False, on_delete=models.CASCADE, verbose_name="User", related_name="favorite_books") book = models.ForeignKey(Book, null=False, blank=False, on_delete=models.CASCADE, verbose_name="Book") def __str__(self): return "{user} added {book} to favorites".format(user=self.user, book=self.book) class SpoilerVote(models.Model): class Meta: # Model for votes of book spoilers verbose_name = "Spoiler Vote" unique_together = ['spoiler', 'user'] spoiler = models.ForeignKey(Spoiler, null=False, blank=False, on_delete=models.CASCADE, verbose_name="Spoiler") user = models.ForeignKey(User, null=False, blank=False, on_delete=models.CASCADE, verbose_name="User", related_name="bookspoiler_votes") choices = ( ('U', 'UP'), ('D', 'DOWN'), ) vote = models.CharField(max_length=1, choices=choices, null=False, blank=False, verbose_name="Vote") def __str__(self): return "{user} liked {book}'s spoiler".format(user=self.user, book=self.spoiler.book.book_title) Following query works fine for FavoriteBook model. most_popular = FavoriteBook.objects.values("book", "book__book_title", "book__year").annotate(count=Count("book")).order_by("-count")[:20] But this one does not work for SpoilerVote model. It returns 1 for each item. SpoilerVote.objects.values("spoiler", "user", "vote").annotate(count=Count("spoiler")).order_by("-count") What am I missing? There is no difference whatsoever. -
Error compressing download.gif: Compressed file not found: /tmp/download_compressed.gif
i am trying to compress the gif file but getting the following error. it says not able to find the file when trying to upload it to s3. MoviePy - Building file /tmp/download_compressed.gif MoviePy - - Generating GIF frames. MoviePy - - Optimizing GIF with ImageMagick. MoviePy - - File ready: /tmp/download_compressed.gif. File does not exist after retries: /tmp/download_compressed.gif Error compressing download.gif: Compressed file not found: /tmp/download_compressed.gif below is my django view that handles the conversion: import os import re import time import tempfile import boto3 from django.conf import settings from django.core.files.base import ContentFile from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from moviepy.editor import VideoFileClip import logging logger = logging.getLogger(__name__) class CompressGifView(APIView): def post(self, request, *args, **kwargs): logger.debug("Received GIF compression request") files = request.FILES.getlist('files') s3 = boto3.client('s3') bucket_name = settings.AWS_STORAGE_BUCKET_NAME folder = 'compressed_gifs/' download_links = [] success = [] converted_file_paths = [] channel_layer = get_channel_layer() def sanitize_group_name(name): sanitized_name = re.sub(r'[^a-zA-Z0-9-_\.]', '_', name) sanitized_name = sanitized_name[:99] return sanitized_name def check_file_existence(file_path): retries = 10 while retries > 0: if os.path.isfile(file_path): logger.debug(f"File exists: {file_path}") return True time.sleep(1) retries -= 1 logger.error(f"File does not exist after retries: {file_path}") return False def … -
removing data migrations in Django
I have been working on a Django app for a client. throughout development there have been data migrations (data insertions/modifications, not structural changes) that have been specific to the client. I am now working on bringing on other clients to use the same app, so I want all reminents of the client specific data removed from the migration files. I feel like the safe and simple way is to keep those migration files and just erase the data migration operations logic. I dont see any reason to keep the data migration logic around anyways, even for the initial client, as it has already been tested and applied in their production environment a while ago. My question: Is this solution sound or are there other points that should be considered? I've searched on the matter, but have not found anything relating to a situation like mine where the data migrations will be introduced to a context where they are incorrect. -
Remote tcp connexion to postgresql not responding
I can't connect to my remote postgresql server. I'm on a local network containing my server (192.168.1.2) and my development workstation (192.168.1.3). I can't connect to my database on port 5432. My server receives TCP frames but does not respond. The other protocols SSH, HTTP are working. However, I can connect to the database on my server on interfaces 127.0.0.1 and 192.168.1.2. On my server, I've modified the pg_hba.conf and postgresql.conf files, adding the lines host and listen_addresses = '*'. Port 5432 is open and listening. The strange thing is that my workstation sends requests on my server's port (tcpdump below) but doesn't respond (no ack). Everything seems correct but it doesn't work. Do you have any idea ? What am I missing? DJANGO SETTINGS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'ering', 'USER': 'marika', 'PASSWORD': '123456789', 'HOST': '192.168.1.2', 'PORT': '5432', } } PG_HBA.CONF local all postgres peer local all all trust local replication all peer host replication all 127.0.0.1/32 scram-sha-256 host replication all ::1/128 scram-sha-256 host all all 0.0.0.0/0 md5 host all all ::/0 md5 SYSTEMCTL STATUS ● postgresql.service - PostgreSQL RDBMS Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enabled) Active: active (exited) since Mon 2024-08-12 11:26:25 CEST; 4min … -
Vector Search with PGVector takes more time
I am using PGVector in Django to make a Vector Search. The time it takes to find the matching row is in few milliseconds, the code I use for it is embedding=self.get_input_embedding(inputText) output=( table.objects.annotate( distance=CosineDistance("embedding",embedding) ) .order_by(CosineDistance("embedding",embedding)) .filter(distance__lt=1-threshold)[:2] ) The output variable is of class type QuerySet. Now to get the value from it I am using the code for neigh in output: print(neigh.Link) Now this block is taking more than 3 seconds. What possibly is the reason for this?