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

30.07.2025
How can I secure my Dockerized Django + PostgreSQL app in production on a VPS using Nginx?

I’m using Django and PostgreSQL for my web project, which I’ve containerized using Docker. I run it on a VPS and serve it with Nginx (running outside Docker). I'm concerned about the security of my PostgreSQL database and want to …

30.07.2025
Unable to properly render ModelSelect2Multiple in modal window

I have a Book model that has a authors field which is a ManyToMany field to Author model. I'm using django-autocomplete-light package to render a select2 widget in my templates that will allow me to select more than one author …

30.07.2025
Uppy with DO Storages on Django

I can not get Uppy AWS to work. I am using DigitalOcean Storage. Here is the HTML (part is GitHub Copilot): <div id="uppy"></div> <script type="module"> import {Uppy, Dashboard, AwsS3} from "https://releases.transloadit.com/uppy/v4.13.3/uppy.min.mjs" const uppy = new Uppy() uppy.use(Dashboard, …

30.07.2025
Django Admin ask for login on every click

Working on a Django project deployed on AWS. In production, I'm facing a session-related issue: When I open the Django admin site (/admin) and log in, everything works smoothly. But if I open the user site (/) in the same …

30.07.2025
Python Wand: MagickReadImage returns false, but did not raise ImageMagick exception

I've got some long-standing code in a Django code base that reads in a PDF and uses Wand to take a screenshot of the first page of the PDF, which is then displayed on the website. We …

30.07.2025
JavaScript Django default scaling using extends index

I'm using Django's template inheritance (extends) in every page of the app. The current design looks too zoomed out, and I want to adjust the default scaling through my index.html, but it didn't work. I also tried using custom CSS, …

29.07.2025
Filter Django RangeField by comparing to a point, not to another range

The PostgreSQL specific model fields docs are very specific about how to compare one RangeField to another range. But how do you compare a range to a single point? For example, if I've got a model with …

29.07.2025
502 Bad Gateway on AWS ELB with Nginx + Django + Gunicorn

Summary of Issue: 502 Bad Gateway from ELB to Django app behind Nginx + Gunicorn on EC2 Environment: Hi, I wonder if anyone can assist. I've been banging my head against a wall for over a week now, I've tried …

28.07.2025
How to use pytest fixtures in single Django TestCase test function

Test yields TypeError: test() missing 1 required positional argument: 'fix' from django.test import TestCase import pytest @pytest.fixture def fix(): return "x" class QueryTestCase(TestCase): def test(self, fix): print(fix) An almost similar case exists but I want the …

28.07.2025
Importing files twice from multiple files

Imagine i have a "first.py" file with some code in it , and then i import it in another python file called "secend.py" then i import the "secend.py" file & "first.py" into "third.py" file ,, Will this cause any …

27.07.2025
Where are these PydanticDeprecatedSince20 and RemovedInDjango60Warning warnings coming from?

I am getting the following output in my warnings summary: venv/lib/python3.11/site-packages/pydantic/_internal/_config.py:323: 15 warnings /Users/darshankalola/Desktop/roon-be/roon-doctor-service/.venv/lib/python3.11/site-packages/pydantic/_internal/_config.py:323: PydanticDeprecatedSince20: Support for class-based `config` is deprecated, use ConfigDict instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.11/migration/ …

27.07.2025
Replacement for migrate --skip-checks

I am having some issues with the latest version of Django. It seems they have removed the --skip-checks option from the manage.py migrate command. The problem I am getting is that the app (that was working on 4.2) is trying …

27.07.2025
Htmx web socket extension not rendering server messages

I'm using the below to render model initial counts on load. consumers.py: from channels.generic.websocket import WebsocketConsumer from django.template.loader import render_to_string from myapp.models import Model1, Model2, Model3, Model4 class DashboardHeaderConsumer(WebsocketConsumer): def update_dashboard_counts(self): stats = [ {'name': 'Model1', 'value': Model1.objects.count()}, {'name': 'Model2', …

27.07.2025
Django + Tailwind CSS deployment failing on Railway with Procfile parsing errors

I'm trying to deploy a Django application with compiled Tailwind CSS to Railway, but I keep getting Procfile parsing errors. The build process works fine (Tailwind compiles successfully), but the deployment fails during the Procfile parsing stage. Error Message Nixpacks …

26.07.2025
404 not found error Django URL with JavaScript fetch function

I'm building a Todo app with Django and JavaScript. I've reached the point where when I click a "trash" button, the note should be deleted, but it shows an error in the console, the reason for which is not clear …

26.07.2025
Django "makemigrations" stuck for ever

When I run python manage.py makemigrations, it just gets stuck. No matter how long I wait, it stays frozen forever—no logs, no output, nothing. I even changed my PostgreSQL database to the default SQLite database in settings.py, but it still …

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 …