"Вопросы и ответы" Django и Python

31.10.2025
Create question with options from same endpoint

So i am making a backend system using DRF in Django, this is my first project in django and drj, i am using django purely as a rest backend i am making a Quiz/mcq application this is from my questions …

31.10.2025
Django difference between aware datetimes across DST

I'm working on a Django application in which I need to calculate the difference between timestamps stored in the DB. This week I run into some problems related to DST. In particular in the following code snippet: tEndUtc = tEnd.astimezone(timezone.utc) …

31.10.2025
Can I use get_or_create() in django to assign a global variable?

I am an intern at a company and we are using django as framework. I was working on a two part register system in which an admin performs the initial registration after which a link is sent to the user …

31.10.2025
Django Celery Beat SQS slow scheduling

Beat seems to be sending the messages into SQS very slowly, about 100/minute. Every Sunday I have a sendout to about 16k users, and they're all booked for 6.30pm. Beat starts picking it up at the expected time, and I …

30.10.2025
Django Mongodb Backend not creating collections and indexes

Summary Running Django migrations against our MongoDB database does not create MongoDB collections or indexes as defined in our app. The command completes without errors, but no collections or indexes are provisioned in MongoDB. Environment Django: 5.2.5 django-mongodb-backend: 5.2.2 Python: …

30.10.2025
How to aggregate hierarchical data efficiently in Django without causing N+1 queries?

I’m working with a hierarchical model structure in Django, where each level can represent a region, district, or village. The structure looks like this: class Location(models.Model): name = models.CharField(max_length=255) parent = models.ForeignKey( 'self', on_delete=models.CASCADE, related_name='children', null=True, blank=True ) def __str__(self): …

29.10.2025
Deploy Django and Nginx under subpath

I'm trying to deploy a Django app with Gunicorn and Nginx under a subpath, I'm inside a corporate network, and the path www.example.com/myapp points to the IP 192.168.192.77:8080 of my PC on the local network (I have no control over …

29.10.2025
Django transaction.atomic() on single operation prevents race conditions?

Why I need to use atomic() when I have only 1 db operation inside atomic block? My AI-assistant tells me that it prevents race conditions, but I don't use select_for_update() inside. It tells that db looks on unique constraints and …

29.10.2025
Can't find xgettext or msguniq but gettext-base is installed

As part of a django project, I need to build translation *.po files, but I have the error CommandError: Can't find xgettext. Make sure you have GNU gettext tools 0.19 or newer installed. when I run django-admin makemessages -a …

28.10.2025
Encoding full payload and decoding in server in REST

Issue WAF is showing some errors due to including some HTML tags in my payload responses (mostly field-like messages and user guides). Sometimes, I am also sending R programming language code to the server, which will just be stored in …

27.10.2025
Deploying Dockerized (React + Django + PostgreSQL ) app with custom license to a client without exposing source code

I am running a test simulation on a virtual server in VirtualBox to see how the procedure of installing a web application using Docker would work on a client server. My stack includes: Frontend: React.js, built into a Docker …

25.10.2025
How to Avoid JWT Collision While Receiving Bearer Token

I am doing a Django project where I am using JWT token for authentication. But the problem is that two different JWT tokens are both valid with the same signature that is provided in the backend with …

25.10.2025
Can't insert rows into Supabase profile table even after creating the RLS policy to do so for the sign up feature

Again, I am quite new to Supabase so I apologize in advance if I don't provide clear details in this post or mess up with some terms or something Basically, I am doing auth using Supabase and have this table …

25.10.2025
Is it possible to force mysql server authentication using django.db.backends.mysql?

It's my first question on stack overflow because I can't find relevant information in Django documentation. Is it possible to force mysql server authentication with ssl using django.db.backends.mysql? I have checked its implementation in Django Github and it seems it …

25.10.2025
How to reuse a Django model for multiple relationships

I want to make a task model and a user model. And I want each task to be able to be related to 3 users. Each task should be related to a creator user, an assignee user, and a verifier …

24.10.2025
How to aggregate a group by query in django?

I'm working with time series data which are represented using this model: class Price: timestamp = models.IntegerField() price = models.FloatField() Assuming timestamp has 1 min interval data, this is how I would resample it to 1 hr: queryset = …

24.10.2025
How to aggregate a group by query in django?

I'm working with time series data which are represented using this model: class Price: timestamp = models.IntegerField() price = models.FloatField() Assuming timestamp has 1 min interval data, this is how I would resample it to 1 hr: queryset = …

24.10.2025
How to integrate JWT authentication with HttpOnly cookies in a Django project that already uses sessions, while keeping roles and permissions unified?

I currently have a monolithic Django project that uses Django’s session-based authentication system for traditional views (login_required, session middleware, etc.). Recently, I’ve added a new application within the same project (also under the same templates directory) that communicates with the …

23.10.2025
How to aggregate a group by queryset in django?

I'm working with time series data which are represented using this model: class Price: timestamp = models.IntegerField() price = models.FloatField() Assuming timestamp has 1 min interval data, this is how I would resample it to 1 hr: queryset = …

23.10.2025
Changing Django Model Field for Hypothesis Generation

I'm testing the generation of an XML file, but it needs to conform to an encoding. I'd like to be able to simple call st.from_model(ExampleModel) and the text fields conform to this encoding without needing to go over each and …

23.10.2025
How can I set a fixed iframe height for custom preview sizes in Wagtail’s page preview?

I’m extending Wagtail’s built-in preview sizes to include some additional device configurations. Wagtail natively supports device_width, but not device_height. I’d like to define both width and height for the preview iframe instead of having it default to height: 100%. Here’s …

22.10.2025
How to enable bulk delete in Wagtail Admin (Wagtail 2.1.1, Django 2.2.28)

I’m currently working on a project using Wagtail 2.1.1 and Django 2.2.28. In Django Admin, there’s a built-in bulk delete action that allows selecting multiple records and deleting them at once. However, in Wagtail Admin, this functionality doesn’t seem to …

22.10.2025
Django-Oscar: UserAddressForm override in oscar fork doesn't work

I need to override UserAddress model. My Steps: Make address app fork python manage.py oscar_fork_app address oscar_fork Override model from django.db import models from django.conf import settings from django.utils.translation import gettext_lazy as _ AUTH_USER_MODEL …

22.10.2025
Django ORM fails to generate valid sql for JSONb contains

Lets start with the error first from my logs: 2025-10-21 19:18:11,380 ERROR api.services.observium_port_status_service Error getting port status from store: invalid input syntax for type json LINE 1: ..." WHERE "api_jsonstatestore"."filter_key_json" @> '''{"type"... ^ DETAIL: Token "'" is invalid. CONTEXT: JSON …

21.10.2025
Menu Items stacking vertically

Stack = Django, PostgreSQL, TailwindCSS 4 using Django-Tailwind (DaisyUI plugin) and Vanilla JavaScript My menu items for desktop (lg screens and above) on the second row are stacking vertically. I don't understand why they aren't horizontal. <div …

21.10.2025
React Native Maps not showing Markers on Android, even though API data is fetched correctly

I'm building a React Native app to display location markers on a map using react-native-maps. I'm using the Google Maps provider on Android. My problem is that the map loads, but the markers are not visible, even though I can …

21.10.2025
Aggregate a group by queryset in Ddjango?

I'm working with time series data which are represented using this model: class Price: timestamp = models.IntegerField() price = models.FloatField() Assuming timestamp has 1 min interval data, this is how I would resample it to 1 hr: queryset = …

20.10.2025
I can only run my backend tests locally because all the instances of the mocked environment are created and into the actual db because of celery

I want to create tests but every time I run a test it triggers celery and celery creates instances into my local db. that means that if I run those tests in the prod or dev servers, then it will …

20.10.2025
Django cannot find static image file

I have a Django project served on AWS EC2, with just one HTML page which is supposed to display one static image (im.jpg) but it doesn't. It does display body text on HTML file (following) but not the image. It …

20.10.2025
How to specify the name while concurrently removing indexes from database

I have some field in my table for which i need to remove indexing. In the django application, i saw that i could do this using the migrations.RemoveIndexConcurrently() method. However im having confusions on how to specify the name attribute …

20.10.2025
Role based access control implementation [closed]

I am developing a food ordering and delivery service and I have four roles in my project admin, customer, rider and manager but I get challenge on implementing role based access control so I would like to ask how to …

20.10.2025
Django ошибка 304

Я новичок в Django, пытался следовать туториалу с Metanit, но почему-то не выходит. urls.py: view.py В settings указал приложение в installed_apps. При запуске и обращении по …

19.10.2025
Trouble connecting my database to Django server on deployment machine

I'm deploying to AWS Linux 2023 and my postgresql database in on aws RDS. I've installed psql and checked if db is accessible in my instance. I've also checked that the environmental variables are fetching exactly as expected in my …

19.10.2025
Celery memory leak in Django — worker memory keeps increasing and not released after tasks complete

I’m using Django + Celery for data crawling tasks, but the memory usage of the Celery worker keeps increasing over time and never goes down after each task is completed. I’m using: celery==5.5.3 Django==5.2.6 Here’s my Celery configuration: …

18.10.2025
Проблема с медиа файлами с Django

Разрабатываю REST API на Django для сайта с товарами, где у каждого продукта может быть несколько медиафайлов (изображения и видео). Реализовал связь один-ко-многим (1:N) между моделями Product и Media. Создал отдельные сериализаторы для Product и Media, но столкнулся с проблемой: …

18.10.2025
Error during Django Deployment: Cannot import 'setuptools.build_meta'

I have encountered this error while deploying my Django project on Render. The error is as follows: pip._vendor.pyproject_hooks._impl.BackendUnavailable: Cannot import 'setuptools.build_meta' I have upgraded setuptools, even reinstalled the package but still can't figure out what the issue is. PS- …

18.10.2025
Mystery lag in completing Django POST request after form.save() completes

One of the forms in my Django application takes a long time to submit, save, and redirect. I'm using a variant of cProfile to measure the time spent on form.clean() and form.save(). It takes <0.1 seconds to run form.clean(), then …

17.10.2025
Certain django-select2 fields won't render when multiple forms are used on single template

I have an issue rendering some select2 fields: When multiple forms with same select2 widget are used within a single template some select2 fields are not rendered as expected (rendered just as normal select field). If I re-initialize one of …

17.10.2025
Custom Permissions in django-ninja which needs to use existing db objects

I am using django-ninja and django-ninja-extra for an api. Currently I have some Schema like so from ninja import schema class SchemaA(Schema) fruit_id: int other_data: str and a controller like so class HasFruitAccess(permissions.BasePermission): def has_permission(self, request: HttpRequest, controller: ControllerBase): …

16.10.2025
How can I share my PostgreSQL changes with teammates after git pull in a Django project?

I'm working on the backend of a web application using Django.Each developer has a local setup of the project, and we all pull updates from GitHub using git pull. I have a question about database changes: Whenever I make changes …