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

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 …

16.10.2025
Velvet: Static Files are searched by path string in urls

This issue refers to Velvet - Django Bootstrap 5 Premium Admin & Dashboard Template If you add a new URL urlpatterns = [ path( "dashboard/", views.velvet_dashboard, name="dashboard" ), # this finds Not Found: /dashboard/static/assets/libs/bootstrap/css/bootstrap.rtl.min.css path( "", views.velvet_dashboard, name="dashboard" …

14.10.2025
Django: User Experience for checking if a person already exists in the database (first and last name, and birthday)

[I'm sure my use case has been addressed somewhere, but I'm not finding it.] In this use case, the user is registering a new person with the following fields: first name, last name, and birthday. If these are the same …

14.10.2025
How to prevent database overload with BlacklistedToken and OutstandingToken models in Django using Simple JWT?

'm working on a Django project using Simple JWT , and I've noticed that every time a user logs in, the generated tokens are stored in the BlacklistedToken and OutstandingToken tables in the database. As more users authenticate and new …

14.10.2025
Where should I put Django pre-flight checks that access the database?

I have a Django app that requires certain items to be in the database before it will run. I'd like to add checks at start time that will fail if these items are not found in the database. Is there …

12.10.2025
Как сбросить пароль в форме изменения пользователя Django

В моем проекте есть базовая модель пользовательского интерфейса. Когда я хочу обновить ее, я заполняю свою форму с помощью instance, где пытаюсь сделать пароль пользователя нулевым, но в любом случае в форме, которую я получаю: "Пароль не установлен. Установить пароль …

12.10.2025
Больше, чем простая проверка формы с помощью Django [duplicate]

Я изучаю Django с помощью небольшого приложения, позволяющего людям бронировать дома для проживания. У меня есть две модели, описывающие дом и бронирование (в настоящее время я работаю без модели "Клиент"): # models.py from django.db import models class Housing(models.Model): …

10.10.2025
Изменение владельца файла .venv, созданного uv внутри Docker

У меня есть приложение Django, созданное с помощью uv, работающее внутри Docker. Я монтирую локальную файловую систему как том в контейнере, используя Docker Compose, чтобы изменения в исходном коде локально запускали перезагрузку приложения в контейнере. Это почти работает. Проблема …

09.10.2025
Электронная почта Django не отправляется — ошибки нет, но сообщения не приходят (при использовании Gmail SMTP)

Я пытаюсь отправлять электронные письма из моего проекта Django, используя SMTP-сервер Gmail. Сервер работает без каких—либо ошибок, и мой код выполняется успешно, но электронные письма никогда не доходят до получателя - даже в папку "спам". Я включил двухэтапную верификацию в …

09.10.2025
Django получает 530, требуется аутентификация 5.7.0, несмотря на использование паролей приложений Google

У меня есть 2fa в Google, я создал пароль, указав правильный адрес электронной почты и пароль от приложения в поле settings.py, но все равно получаю ошибку аутентификации. Пробовал и 587 (TLS=True), и 465 (SSL=True), но, похоже, ничего не изменилось. settings.py: …

09.10.2025
Как я могу правильно реализовать ManifestStaticFilesStorage в Django?

Я пытаюсь реализовать ManifestStaticFilesStorage в моем проекте Django. Из того, что я видел, это должно быть просто, но оно ведет себя не так, как я ожидал. Во-первых, у меня есть DEBUG=os.getenv("DEBUG", "False").lower() == "true" В моем файле settings.py с …

09.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 = …

08.10.2025
Как выполнить поиск по нескольким полям в django_opensearch_dsl

У меня есть сервер opensearch, на котором я хочу выполнять поиск элементов и применять некоторые фильтры к поиску: search = Item.search().query("match", name="test") Мне нужно искать элементы по нескольким фильтрам, таким как название, дата, местоположение и т.д. Для этого мне …

08.10.2025
Почему pytest не удается разрешить ссылки на связанные модели в пакете Django?

У меня есть устанавливаемый пакет Django, который я собрал и начал писать для него тесты. Я использую pytest-django. Однако, когда я запускаю тесты, почти все тесты завершаются неудачей, и я продолжаю получать эту ошибку: - Для справки, это мой conftest.py …

08.10.2025
Как интегрировать OpenAI GPT API в проект Django REST Framework?

Я создаю проект Django REST Framework (DRF) и хочу интегрировать OpenAI GPT API для предоставления пользователям ответов на основе искусственного интеллекта. Я пробовал настроить вызов API с помощью библиотеки запросов Python, а также с помощью официального пакета openai Python, но …

07.10.2025
Django runserver возвращает ERR_CONNECTION_RESET в Windows 11 (никаких ошибок в терминале)

Я изучаю Django и пытаюсь запустить свой проект локально в Windows 11. Когда я запускаю сервер, он работает без каких-либо ошибок, но когда я пытаюсь открыть его в своем браузере (127.0.0.1:8000 или 127.0.0.1:8001), я получаю это сообщение: Hmmm… can’t reach …

07.10.2025
Как аутентифицировать запросы с помощью django allauth (безголовый)

Я всегда получаю ответ 401 после входа в django-allauth в сеансе (и других конечных точках). Смотрите пример кода: def login(email, password): response = requests.post( f'{baseurl}/api/allauth/app/v1/auth/login', headers={ 'accept': 'application/json', 'Content-Type': 'application/json', }, json={ 'password': password, 'email': email } ) return response …

07.10.2025
Выделите пораженные участки легких на рентгеновских снимках грудной клетки с помощью Python, Django и CNN в веб-приложении для выявления пневмонии [закрыто]

Наша команда создает веб-систему обнаружения пневмонии, используя Python, Django и CNN. Модель классифицирует рентгеновские снимки грудной клетки как пневмонию или нормальную форму, но теперь мы хотим выделить пораженные участки легких для медицинских работников. Задачи: Создание тепловых карт/выделений (например, Grad-CAM). Эффективная …

05.10.2025
Использование Django [закрыто]

Как именно Django используется на рабочих серверах? Используется ли он в основном с rest_framework для создания API-интерфейсов или используется просто как полнофункциональный фреймворк с рендерингом шаблонов. Спрашиваю, потому что шаблоны в prod кажутся неправильными. Хотите узнать общий случай использования Django