"Вопросы и ответы" Django и Python, страница 3

26.07.2025
Django filter an m2m relation by a list of inputs (which must all match)

Let's take some Store and Book models as examples: class Book(Model): title = CharField(...) ... class Store(Model): books = ManyToManyField('Book', blank=True, related_name='stores') .... I receive a list of book titles and must return stores linked to those books. I …

25.07.2025
How I push Django database sqlite3 and media folder on github for production server

The problem occurs when I delete the db.sqlite3 and media on .gitignore file. and write add command git add -A. the error comes fatal:adding files fail PS C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\Blog> git add -A error: read …

25.07.2025
Django REST Framework `pagination_class` on ViewSet is ignored

Describe the Problem I have a ModelViewSet in Django REST Framework designed to return a list of Order objects. To improve performance, I'm trying to implement custom pagination that limits the results to 65 per page. Despite setting the pagination_class …

25.07.2025
GetCSRFToken is not defined error, JavaScript

This is the part of the code in the Django + JavaScript Todo App that is responsible for deleting a note. I need a csrftoken for this, but the JS is showing me an error in the console. What did …

25.07.2025
How DRF undestand which field in serialazer.py is related to which model field?

Imagine i have a super simple serializer.py file : and i just want to use it ! nothing special .. so im going to write something like this (with …

25.07.2025
Results of Questionnaire to be downloaded as a spreadsheet

So i have this Model namely Questionnaire in models.py file of a Django project class Questionnaire(models.Model): title = models.CharField(max_length=200) description = models.TextField(blank=True, null=True) formula = models.CharField( max_length=200, default='{total}', help_text="Formula to calculate the total score for this questionnaire. Use {total} and …

24.07.2025
Django google-auth-oauthlib insecure_transport error on Cloud Workstations despite HTTPS and SECURE_PROXY_SSL_HEADER

I'm developing a Django application on Firebase Studio environment. I'm trying to implement Google OAuth 2.0 for my users (doctors) to connect their Google Calendar accounts using the google-auth-oauthlib library. The application is accessed via the public HTTPS URL provided …

24.07.2025
Django, HTMX, class based generic views, querysets and pagination

I think this is as much a question about minimalism and efficiency, but anyway... I have a generic ListView that I'm using, along with HTMX which I'm a first time user of, but loving it so far! That said, I …

24.07.2025
При переносе данных PostgreSQL на render.com не работают миграции

Я деплою Django-проект на Render.com, база данных — PostgreSQL (через Render Database). Что уже работает: Проект успешно билдится Сайт открывается Стили грузятся Проблема: После деплоя база данных пустая — нет товаров, пользователей и т.д., хотя локально они есть. …

23.07.2025
How to get a billing cycle period between the 26th of the previous month and the 25th of the current month using Python (timezone-aware)?

The Problem I'm building a billing system in Django, and I need to calculate the billing period for each invoice. Our business rule is simple: The billing cycle starts on the 26th of the previous month at midnight (00:00:00); …

23.07.2025
How to parse multipart/form-data from a put request in django

I want to submit a form to my backend and use the form data as the initial value for my form. Simple stuff if you are using a POST request: def intervals(request, **kwargs): form = MyForm(initial=request.POST) However, …

23.07.2025
How many keys can I use store in Django file-based cache before it becomes a performance bottleneck?

I'm working with a large number of small-sized data entries (typically 2–3 KB each) and I'm using Django's file-based cache backend for storage. I would like to understand the scalability limits of this approach. Specifically: Is there a practical or …

23.07.2025
How to swap between detail views for user specific datasets in django (python)?

On a Table (lets call it Items) I open the detail views for the item. On the detail view I want a "next" and a "previous" button. The button should open the next items detail view. I cannot just traverse …

22.07.2025
Is it possible to run Django migrations on a Cloud SQL replica without being the owner of the table?

I'm using Google Cloud SQL for PostgreSQL as an external primary replica, with data being replicated continuously from a self-managed PostgreSQL source using Database Migration Service (DMS) in CDC mode. I connected a Django project to this replica and tried …

22.07.2025
Why is my Cloud SQL external replica not reflecting schema changes (like new columns) after Django migrations?

I'm using Google Cloud Database Migration Service (DMS) to replicate data from a self-managed PostgreSQL database into a Cloud SQL for PostgreSQL instance, configured as an external primary replica. The migration job is running in CDC mode (Change Data Capture), …

22.07.2025
Django won't apply null=True changes on fields when running makemigrations and migrate

I’m working on a Django project and I’m facing an issue: I modified several fields in one of my models to be null=True, but after running makemigrations and migrate, the changes are not reflected in the database. I have a …

21.07.2025
Django ORM, seeding users and related objects by OneToOneField

I am designing a django application for educational purposes. I've come up with creating a fake banking application. The idea is to have a User<->BankAccount link by a OneToOneField. Similarly, to have User<->UserProfile link by a OneToOneField. Attached is my …

21.07.2025
How to prevent Django from generating migrations when using dynamic GoogleCloudStorage in a FileField?

We’re working on a Django project that stores video files in Google Cloud Storage using a FileField. In our model, we define a default bucket storage like this: from storages.backends.gcloud import GoogleCloudStorage from django.conf import settings DEFAULT_STORAGE = …

21.07.2025
Django Celery with prefork workers breaks OpenTelemetry metrics

I have a Django application I wanted to instrument with OpenTelemetry for traces and metrics. I created an otel_config.py file next to my manage.py with this content: # resources def get_default_service_instance_id(): try: hostname = socket.gethostname() or "unknown-host" except …

21.07.2025
Moving from Django-WSGI to ASGI/Uvicorn: issue with AppConfig.ready() being called synchronously in asynchronous context

I'm moving my application views to asynchronous calls as they are requesting a number of data from the database. When running the async views from the wsgi server, everything is working according to expectations. But to be able to really …

21.07.2025
Django message not showing up in template

I’m using Django 5.2.4, and my login_user view sets an error message with messages.error when authentication fails, but it doesn’t appear in the template (login page) after redirecting. App urls: from django.urls import path from django.shortcuts import redirect from . …

20.07.2025
How to show in django template data from connected models?

I have a models: class Publication(models.Model): pub_text = models.TextField(null=True, blank=True) pub_date = models.DateTimeField(auto_now_add=True) pub_author = models.ForeignKey(User, on_delete=models.CASCADE) coor_text = models.CharField(null=True, blank=True) coor_adress = models.CharField(null=True, blank=True) coor_coordinates = models.CharField(null=True, blank=True) class Image(models.Model): image = models.ImageField(upload_to='images', null=True) image_to_pub = models.ForeignKey(Publication, on_delete=models.CASCADE, null=True, …

20.07.2025
Django-import-export id auto generated by the package during insert?

I'm using django-import-export and trying to work it with multi-thread concurrency. I tried logging the sql queries and notice that INSERT query has id values generated as well. INSERT INTO "lprovider" ("id", "npi", "provider_id", "first_name", "last_name") VALUES (278082, '1345', …

20.07.2025
Postgres indexing fails in Django

Tried to set db_index=True, HashIndex and BrinIndex, nothing works, indexes by Seq Scan, there are 1000 records in the database, all migrations are completed. Model code: from django.db import models from django.utils import timezone from django.contrib.postgres.indexes import BrinIndex, HashIndex class …

19.07.2025
Bad Request /api/accounts/register/ HTTP/1.1" 400 50

I am a newbie to ReactJS and Django REST Framework. I am trying to connect the frontend registration form to a backend API to no avail; I keep getting "POST /api/accounts/register/ HTTP/1.1" 400 50' error. The following are codes: endpoints: …

19.07.2025
Ошибка django.db.utils.NotSupportedError: метод доступа "hash" не поддерживает индексы по многим столбцам

Пишу проект на Django, используя бд от postgres, при попытке мигрировать модели возникает ошибка "django.db.utils.NotSupportedError: метод доступа "hash" не поддерживает индексы по многим столбцам", до этого попытался сделать хэш-индексирование по двум столбцам, после чего она и появилась. Пробовал удалять миграции, …

19.07.2025
Не получается отправить данные на frontend с backend для подгрузки новой страницы. В чем причина?

Пишу сайт на Django, DRF, Redis, Nginx, Guvicorn. Столкнулся с такой проблемой: У меня есть frontend, который в этом блоке const ws = new WebSocket( `wss://storisbro.com/ws/auth_status/?token=${token}` ); ws.onmessage = (event) => { const data = JSON.parse(event.data); console.log("Auth status changed:", data["authenticated"]); …

18.07.2025
Why are some folders and files still red in PyCharm even though the Django project works correctly?

I'm working on a Django project in PyCharm, and although everything works fine (including migrations, interpreter setup, Django installation, and manage.py is in the correct place), some folders and .py files like models.py, admin.py, etc., still appear in red in …

18.07.2025
Email verification in django python

I try to make email verification in django, everyting works correctly, but if user creates account with someone other's email and if user will not confirm email, owner of this email will not be able to register because account is …

17.07.2025
Activate script missing from Python virtual environment (venv) on Ubuntu 22.04 with Python 3.12

I'm trying to deploy a Django project on my Ubuntu server using a virtual environment. I created a directory named ae9f7a37e98d4a8f98643ced843d71d7_venv, but when I try to activate it using: source /www/wwwroot/ddlvv/ae9f7a37e98d4a8f98643ced843d71d7_venv/bin/activate I get this error: -bash: /www/wwwroot/ddlvv/ae9f7a37e98d4a8f98643ced843d71d7_venv/bin/activate: No such file …

17.07.2025
Django-tenants: relation "journal_nav_topnavitem" does not exist even after adding app to SHARED_APPS and running migrate_schemas --shared

I'm working on a multi-tenant Django project using django-tenants with Django 3.2.16. I created an app called journal_nav and initially added it only to TENANT_APPS. Later, I moved it to SHARED_APPS because it provides a common navigation bar for all …

17.07.2025
Cannot find settings module in mod_wsgi (Apache2 on Ubuntu with django)

I am serving a Python app using Django through an Apache2 server. I have the wsgi.py file in a directory home/peter/django-apps/anaaccess/anaaccess/ana_access/wsgi.py I have a venv in home/peter/django-apps/anaaccess/anaaccess/myenv into which I have installed mod_wsgi and django, etc. I have put …

16.07.2025
In Django form, set ModelChoiceField selection when form renders

I have been tasked with making changes to a django project's form. On this form is a ModelChoiceField. The customer request is to populate this field with the text of a value in its selection list when that value is …

16.07.2025
Solution to not split logic in django to solve N+1 queries

Here are some of my models: class CustomUser(AbstractUser): def correct_date(self, date=None): res = self.dates.order_by("date").all() if not len(res): return None return res[len(res) - 1] class Date(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name="dates") date = models.DateField(auto_now_add=True) To fix N+1 queries …

16.07.2025
Django send_mail() / EmailMessage with Gmail SMTP has 4-minute delay for new email recipients

I’m facing a consistent email delivery delay when using Django’s built-in send_mail() or EmailMessage functions with Gmail SMTP. 🔧Setup: Backend: Django (tested with both send_mail() and EmailMessage) SMTP: smtp.gmail.com with App Passwords Recipients: New or first-time email addresses (e.g., …

15.07.2025
Django inline formset won't save form appended via JS

I'm trying to create page where "parent" and related object may be updated. Due to some specific business logic "child" form has specific couple of fields where only one of them may be selected. So when option selected JS issues …

14.07.2025
How to handle sorting, filtering and pagination in the same ListView

GitHub link: https://github.com/IgorArnaut/Django-ListView-Pagination-Search-Sorting-Issue I have an issue with the ListView. I have pagination, side form for filtering and a form with select for sorting in a single view. These 3 use get method and are "handled" in …

14.07.2025
Want a UI for archived user and therapists , [closed]

I have two models in my Django project: User and Therapist. Both have long lists of records in the database. Each model includes an archived_at field (a DateTimeField) that I use to mark when a user or therapist has been …

14.07.2025
Background daemon in celery without task explosions

I'm always having a hassle trying to have celery jobs scan the database for work, but to not have things done twice or submission explosions. The issue resides in that: periodic celery-beat jobs just keep submitting, even if there …

14.07.2025
Can pyHanko digitally sign HTML content directly, or is PDF conversion required?

I’m working on a Django web application where documents are generated and displayed using styled HTML templates (e.g., for formal printable forms). These are rendered in the browser with proper formatting and layout. I am using pyHanko (version 0.29.0) to …