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

18.03.2026
Django tests in GitLab CI always use PostgreSQL instead of SQLite despite APP_ENV override

I am running Django tests inside GitLab CI and trying to switch between SQLite (for local/test) and PostgreSQL (for production). My settings structure looks like this: settings/_init_.py: import os APP_ENV = os.getenv("APP_ENV", "local") if APP_ENV == "local": from …

18.03.2026
Serializers Prefetch in View

In Django / DRF, we can provide Prefetch, but is it the role of the serializer to have "good" datas. For example I have this basic code: from rest_framework import generics, serializers from app.models import Client class ClientListCreate(generics.ListCreateAPIView): …

17.03.2026
How to separate local and production settings in django?

I have .env.local and .env.prod files, and I've split settings.py into base, local, and production. Running a Django app with production settings works without any problems (thanks to docker), but I'm not entirely sure how to easily run it with …

17.03.2026
How to fix issue with passing class instances between methods in Python (Django context)?

I am practicing Object-Oriented Programming in Python (Django context). I have two classes: one represents a ProjectIdea, and another represents a ProjectIdeaBoard. I want to: Add (pin) a ProjectIdea instance to the board Remove (unpin) a specific instance …

16.03.2026
How to properly store image dimensions in Django

I have the following model: from django_resized import ResizedImageField class PostImage(models.Model): image = ResizedImageField( size=[1200, 1200], quality=85, upload_to="post_images/", blank=True, null=True, force_format="WEBP", keep_meta=False, width_field="width", height_field="height", ) width = models.IntegerField(null=True, blank=True) height = models.IntegerField(null=True, blank=True) Now the problem I …

16.03.2026
ModuleNotFoundError: No module named 'pkg_resources' With Django Project

ModuleNotFoundError: No module named 'pkg_resources' when trying to run Django Application. This error simply indicates a version mismatch. Django support may not work with the latest Python versions because support still remains in earlier versions of python. So all you …

15.03.2026
Handling user registration and subsequent profile creation

I have a custom User model with a role field and respective [Role]Profile models: class User(AbstractUser): role = models.CharField() # Other fields class TeacherProfile(models.Model): # profile_picture and other fields class StudentProfile(models.Model): # for now just a reference to …

14.03.2026
Obtener usuarios de keycloak

Me pueden ayudar a cómo obtener usuarios de un directorio activo esto es porque voy a consumir api keycloak porque no tengo el control de este, entonces la idea también es que a cada unas de las cuentas es colocarle …

14.03.2026
Implementing HTMX in a Django app: Should I use two templates per view?

When trying to integrate HTMX into my Django app, I'm facing a design issue. My base.html file contains fixed layout elements (a navigation bar and a title). I created a container section with the ID #work-area, which needs to update …

12.03.2026
Django vs FastAPI for building a Retrieval-Augmented Generation (RAG) system [closed]

I want to start building a Retrieval-Augmented Generation (RAG) system that can answer questions based on custom data (for example documents, PDFs, or internal knowledge bases). My current backend experience is mainly with Django and FastAPI. I have built REST …

12.03.2026
Best practice for managing magic strings in Django JsonResponse keys/values

I have a Django view that returns JSON responses: def post(self, request, post_id): post = get_object_or_404(Post, pk=post_id) if post.is_pub_date_future(): return JsonResponse({ 'result': 'failure', # magic string 'message': 'No posts available to dislike' # magic string }, status=404) post.dislikes = F("dislikes") …

10.03.2026
How do you handle POST requests in Django

How do you handle POST requests in Django on PythonAnywhere? The help pages only seem to cover GET requests (which work fine). Got various errors, currently 'Forbidden (Referer checking failed - no Referer.)'. Does urls.py work the same way for …

09.03.2026
How to fix ModuleNotFoundError in Python? [duplicate]

I am trying to run a Python script on my system but I get the error "ModuleNotFoundError: No module named 'django'". I installed Python recently and I am using the command prompt to run the script. When I try to …

08.03.2026
Give customized Context to own templates for predefined Django Reset Password Classes

I am relatively new do django. I try to test my abilities by slightly altering a simple social media app, I learned at a course. In my app I always want to see the index page with the posts and …

08.03.2026
How to make Django Models store `DateTimeField` without microseconds?

I would like store a date in the format M-D, H:M. Is there a way to achieve that with Django Models without using templating and filters or datetime? Code: date = models.DateTimeField(auto_now=True) Output: 2026-03-07 21:52:34.765959 …

07.03.2026
Getting TemplateDoesNotExist for an included template that already exists

I have these template settings in the realestate/settings.py: TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [BASE_DIR / "templates"], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] And this template partial that includes …

07.03.2026
Django version upgrade while using Django River 3.3.0

Currently, the project I’m working on uses Django River 3.3.0 and Django 3.2.19. Is it possible to upgrade Django to version 4? If we do that, are there any potential issues or risks? I’ve been assigned to maintain …

07.03.2026
Cannot Read Data from Nested Serializer in Django REST Framework

Models.py class Post(models.Model): content = models.TextField() created = models.DateTimeField(auto_now_add=True) suspended = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE) class Follow(models.Model): follower = models.ForeignKey(User, related_name='followings', on_delete=models.CASCADE) following = models.ForeignKey(User, related_name='followers', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) class Meta: unique_together = ('follower', 'following') …

06.03.2026
Using Django Admin vs building a custom React admin panel for an online pharmacy website

I am working on an online pharmacy website with the following stack: Backend: Django Frontend (customer interface): React Currently, I am thinking about how to implement the admin panel for managing the website. My question is: …

05.03.2026
How to setup celery beat in django project

I am new to Django and Celery. I am trying to implement a periodic task that flushes data from Redis to ClickHouse every 5 seconds. I am also new to a project that im working on , there is …

04.03.2026
What is the actual difference in using composition versus inheritance?

I am trying to learn inheritance versus composition the hard way. So far, I have understood that composition involves using object reference inside a class. So I asked myself, why did not we choose to use composition in Django for, …

03.03.2026
Gettext does not translate validation error messages in __init__

I am making a real estate Django app in my language (Serbian). I set the project language into Serbian. realestate\settings.py: # Internationalization # https://docs.djangoproject.com/en/5.2/topics/i18n/ LANGUAGE_CODE = "sr" LANGUAGES = [ ("sr", "Serbian"), ("en", "English") ] LOCALE_PATHS = (BASE_DIR …

27.02.2026
Rspack is too slow

First some context: I'm working on a large Django project, where jQuery, Javascript, React and SCSS is used. I first used Webpack but each build took about 3 to 5 minutes, and working in dev mode with it isn't really …

26.02.2026
Django DRF Network Based

I have three networks; A, B, and C. A will contain all fields and will be the single source of truth. B will contain a couple of fields from A, and C will contain much less than A and B. …

25.02.2026
WhatsApp Cloud API: Can I send PDF using public URL in Django backend or must upload media first?

I am integrating WhatsApp Cloud API in a Django backend. I want to send a PDF document message. Instead of uploading media to Meta and using media_id, I want to pass my production file URL in document.link. Questions: 1.Does WhatsApp …

25.02.2026
Cap the number of model rows without a race condition

I'm writing a Django app to accept webmentions. New webmentions get placed into a model called "Pending" until the admin runs a verification action on them. Successfully verified rows are then deleted from "Pending" and moved over …

22.02.2026
Deploying Django backend and React frontend completely free — production-ready options?

I have a Django backend (REST API) and a React frontend. I want to deploy this project for a portfolio, but I would prefer to use only free hosting options (no paid subscriptions). Requirements: - Free hosting for Django backend …

21.02.2026
PyCharm не видит импорт представлений в Django (Unresolved reference / ModuleNotFoundError)

PyCharm выдает ошибку при импорте функций- представлений в Django- проекте: Думал ошибка интерпретатора, добавил интерпретатор из виртуального окружения, не помогло: Добавил __init__.py в …

20.02.2026
Django on Elastic Beanstalk not detecting RDS environment variables (falls back to SQLite)

I am deploying a Django app to AWS Elastic Beanstalk and connecting it to an RDS PostgreSQL database. My Django settings are configured to use PostgreSQL only if RDS_DB_NAME exists in os.environ, otherwise it falls back to SQLite. However, even …

17.02.2026
How to synchronize a locale until a defined level/page?

I’d like to keep the locale synchronization mostly as it is, but I’d like to tell Wagtail Localize to ignore all pages under, say, Lessons: Root > Units > Lessons || [lesson 1] So that lesson pages created under Lessons …

16.02.2026
Why am I getting this key error when using django-formtools and django-allauth together

So I am trying to create multi-step signup wizard using django-formtools and django-allauth. I am using the SessionWizardView from formtools and just trying to use allauth's functionality for signup. I'm not using its standard one page signup flow or its …

14.02.2026
How to hide GraphQL exceptions in strawberry and Django?

I am using GraphQL with strawberry in my Django project. When an exception is raised, the error is shown in the terminal like the server errors. But if a user make mistakes while creating a query, It shouldn't show like …

12.02.2026
Django add to cart function

How i create add to cart function? Using request.method or perform an action when click add to cart button? html <form method="post" action="" class="w-full"> {% csrf_token %} <div class="m-3"> <label for="quantity" class="font-bold">Quantity:</label> <input min="0" max="{{item.stock}}" value="1"> </div> <div class=" …

11.02.2026
How can I use Django Allauth and Google Identity Services (GSI) simultaneously for Google login?

I have a Django project where I want to support Google login in two ways: Classic OAuth redirect flow using Django Allauth. Google One Tap / GSI login. I tried using the same Google OAuth client ID for …

11.02.2026
How to create a custom activity logs of user [closed]

I ma making a help moduel and i want activity logs for this Audit trail Who created which user Who updated what field Company activity history CRM history Help module tracking

08.02.2026
Can this query be expressed in Django?

I have the following set of models (simplified and renamed for the purpose of this question). A lot of other functionality has already been built on top of them so wholesale changes aren't possible, though small tweaks could be. <pre …

06.02.2026
Django , save_model , admin

Okay the issue i am facing is that i am being able to add and save a user , no problem in that and once created , than i can easily assign therapist to that user again no problem , …

05.02.2026
Managing Database Connections in a Microservice Architecture with Django

I am designing a microservice architecture using Django and I have encountered a major challenge in data management. I would appreciate it if you could share your experience and perspective. We have several separate services, each with its own database. …

04.02.2026
Telegram OAuth with django

Im trying to integrate telegram oauth into my application, currently it successfully log in in telegram, but django doesnt received any data in callback, I have tryied many methods, but without any results views.py def telegram_callback(request): data = request.GET.dict() print('Telegram …

03.02.2026
Django project assistance

I am a college student who is new to Django development. I wanted some help from the experienced developers . When I am creating a new Django project on pycharm and Choosing to create it in a new enviornment …