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

16.12.2025
Celery crashes when PgBouncer closes idle connections (idle timeouts enabled)

I’m encountering an issue when running Celery with PgBouncer and PostgreSQL after enabling idle connection timeouts. My stack includes: Django (served via Tornado) Celery (workers + beat) PostgreSQL PgBouncer (in front of PostgreSQL) Due …

16.12.2025
Django Deployment on Render: ModuleNotFoundError for WSGI Application The Problem

Demo of the Project The Problem I am attempting to deploy a Django portfolio project to Render. While the project runs perfectly on my local machine using python manage.py runserver, the deployment fails during the build process. …

15.12.2025
My Journey as a Beginner Web Developer – Need Advice [closed]

As a beginner web developer, I started my journey with HTML, PHP, and MySQL. I built only one real project, a school management system . One day, I saw someone working with React as a front-end developer. That moment really …

15.12.2025
"No module named django_heroku" (or django_on_heroku) error

I'm trying to install OWASP PyGoat, and then create a secure version of it. I followed method 2 on the repository's site (https://github.com/adeyosemanputra/pygoat?tab=readme-ov-file#method-2), but running the "python3 manage.py migrate" command yielded the error message in this post's …

15.12.2025
When building platforms with multiple Python services (FastAPI, Flask, Django, internal APIs), we kept facing the same issues:

When building platforms with multiple Python services (FastAPI, Flask, Django, internal APIs), we kept facing the same issues: • Authentication duplicated across services • Roles and permissions drifting over time • Weak tenant isolation • No clear …

13.12.2025
I just couldn't connect Railway volume With my django-Project

Here in settings.py I've added if os.environ.get("MOUNT_MEDIA"): MEDIA_ROOT = "/app/media" print("Using Railway mounted volume for MEDIA_ROOT") else: MEDIA_ROOT = BASE_DIR / "media" print("Using local folder for MEDIA_ROOT") MEDIA_URL = "/media/" in urls.py …

11.12.2025
How to set table column width to django admin list_display?

I want column foo (TextField 2500 chars) to have a width of 30% in admin view. Yet whatever I try, the columns widths remain equal (50% / 50%). td.foo {width: 30%;} has no effect at all. admin.py: class …

10.12.2025
How to see changes in django admin base.css

I want to change some css in static/admin/css/base.css After some attempts I now fail to understand the static-file concept at all. As a matter of fact I can delete the whole static directory without any effect/error …

09.12.2025
Is it a bad idea to use the builder pattern to construct elasticsearch queries in Python/Django?

So here's the issue. I am maintaining a somewhat large Django app and am tasked with creating a search bar that relies on elastic search data and need to in the near future convert a large number of Django DB …

09.12.2025
Django / Serializer - How to pass label attached to choice field in API?

I am trying to get the label attached to the relevant interger for the choice field. Although the API returns the interger, I cannot seem to be able to return the actual label value. This is the current return: [ …

09.12.2025
Optimization django admin panel queries with select_related and prefetch_related

These are my django models (only the FK s are written) class SellerBuyable(TimeStampMixin, GBSoftDeleteModel): seller = models.ForeignKey(Seller,related_name="seller_buyables",on_delete=models.CASCADE, null=True) buyable = models.ForeignKey(Buyable,on_delete=models.CASCADE,null=True,related_name="seller_buyables",related_query_name='seller_buyable') ... class CampaignItem(TimeStampMixin, GBSoftDeleteModel): campaign = models.ForeignKey(Campaign, related_name='items', on_delete=models.CASCADE) item = models.ForeignKey(SellerBuyable, on_delete=models.CASCADE, null=False) ... class Campaign(TimeStampMixin, …

09.12.2025
How to mock django timezone.now in a abstract model

I'm unable to mock timezone.now in the model's created field. The test fails due unmocked/current datetime. I tried patch('django.utils.timezone.now') to no avail. # app/models.py from django.utils import timezone class BaseModel(models.Model): created = models.DateTimeField(default=timezone.now, editable=False) class Meta: abstract = …

09.12.2025
Имя проекта в django/admin располагается между скобок " (' ',) ", как исправить?

При создании и переименовании проекта ("Project") в админ-панели Джанго получается вместо простого "Заказ" - "('Заказ',)". Кнопка добавления ещё одного заказа так же обрамляется лишними скобками и кавычками + запятая ("Добавить ('Заказ',)"). Почему так происходит, учитывая, что в поле "Выберите Заказ …

09.12.2025
Using group_by to find sum in Django

I'm working on a website to track music practice and I'm trying to set up a query to show how many minutes you've spent with a certain instrument or song. I modeled this behavior using Khan Academy (to test the …

08.12.2025
Storing WAV recording to disk plays as static

I'm recording voice via jquery then sending it to django view: views.py ... elif voice_value: #get voice voice_value = request.FILES.get('sound_file.wav') #read as bytes file_content_bytes = voice_value.read() #using pydub audio_bytes = file_content_bytes # Replace with your actual audio data audio_segment …

08.12.2025
Could not translate host name to address

When I run python manage.py migrate I get this error: (venv) mac@MACs-MBP-2 backend % python manage.py migrate Traceback (most recent call last): File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 279, in ensure_connection self.connect() File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File …

08.12.2025
How to disable localization ONLY in Django admin (specifically /admin/jsi18n requests) while keeping it in the main site?

How to disable localization ONLY in Django admin (specifically /admin/jsi18n requests) while keeping it in the main site? I experiencing 503 errors on our production server due to a high volume of requests to the /admin/jsi18n endpoint when multiple …

08.12.2025
Django Allauth Google OAuth: MultipleObjectsReturned even though no duplicates in MySQL

I’m using Django + MySQL with django-allauth and Google OAuth. Login fails with this error: MultipleObjectsReturned: get() returned more than one SocialAccount The confusing part is that the database does not contain duplicates. Here is what I checked: 1. No …

07.12.2025
When are user permissions ready? - trying to assign permission in post-migration signal

Fairly new to django so there must be a lot I have no idea about. How can I assign user related permissions to user groups in a post migration signal? I have read everywhere that post migration signal can work …

06.12.2025
"You cannot access body after reading from request's data stream"

I have a piece of code that sends a json to the server but form.onsubmit = async (e) => { e.preventDefault(); const formData = new FormData(form); const response = await fetch('api/get-comments/', { method: 'POST', body: formData }); if …

04.12.2025
Why does using Python’s print() function cause a rendering error in Django, and what should be passed to render() instead?

Problem Code Snippet (Python: Django)- def home(request): data = {"msg": "Hello"} result = print(data) # Problematic line return render(request, "index.html", result) # why render? Is there any other way?

03.12.2025
Django Admin: User without permissions can still see a model (UserIncomeSupportDocument) — how to hide it?

I have a Django Admin setup where a Marketing user should only be allowed to view Clients and Therapists. However, even after removing all permissions related to UserIncomeSupportDocument, the Marketing user can still see the model in the Django Admin …

03.12.2025
How Should I manage AI functions and business logic in back-end efficiently

My recent project is a AI Gym trainer app and I am in charge of the back-end. The project purpose is to let user get an AI Gym trainer who guide them daily with personalized suggestions. The main AI tasks …

02.12.2025
Failed import for drf_nested_routers

This import in urls.py gives me an error from drf_nested_routers import DefaultRouter as NestedDefaultRouter Import "drf_nested_routers" could not be resolved however the drf_nested_routers it is installed venv as in inside my requirements.txt file

02.12.2025
Django 3-Tier Nested Modeling

I have a problem where I need a deeply nested model. I have a model named Theme (it's called something else), and in theme I can have many Types. In a Type I can have many or none SubTypes. In …

02.12.2025
Solving the circular problem in Django models

Acconts/models.py class UserX(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_activ = models.BooleanField(default=True) is_verified = models.BooleanField(default=False) # user_follower= models.ManyToManyField("self", through="friends.Follower", related_name="folowers_user", symmetrical=False) objects = ManageUserX() USERNAME_FIELD = 'username' save_p = models.ManyToManyField(through='posts.SavePosts',to='posts.Posts', related_name='save', blank=True, null=True, default = …

30.11.2025
Best practice to switch between development and production urls when using Vue/Vite and Django

I want to build a website with Vue/Vite as frontend and Django as a backend. When my frontend needs to get data from the backend I currently do something like this (which works perfectly fine): const response = …

29.11.2025
How to disable Celery startup logs?

I'm getting a bunch of logs like this: [2025-11-29 16:13:15,731] def group(self, tasks, result, group_id, partial_args, add_to_parent=0): return 1 [2025-11-29 16:13:15,732] def xmap(task, it): return 1 [2025-11-29 16:13:15,732] def backend_cleanup(): return 1 I don't need these logs. It's useless …

28.11.2025
Problem connecting djangoapi with react native mobile with django api

This is my first time here asking for help!!!, My name is Pedro, is a pleasure to be here. So. I made a system to help the company with a task work, and hopefully, be noticed to work with the …

28.11.2025
Filter dates using foreignkey Django and Python

I need to filter a variable between two models using a foreign key. models.py class Vuelo(models.Model): fecha_de_vuelo = models.CharField(max_length=50) ....... class Novedad(models.Model): fecha_de_vuelo_novedad = models.ForeignKey(Vuelo, on_delete=models.CASCADE, related_name="fecha_de_vuelo_novedad", null=True, editable=False) comandante_novedad = ...... view.py def buscar_reporte_demoras(request): …

28.11.2025
Filter dates using foreignkey Django

I need to filter a variable between two models using a foreign key. models.py class Vuelo(models.Model): fecha_de_vuelo = models.CharField(max_length=50) ....... class Novedad(models.Model): fecha_de_vuelo_novedad = models.ForeignKey(Vuelo, on_delete=models.CASCADE, related_name="fecha_de_vuelo_novedad", null=True, editable=False) comandante_novedad = ...... view.py def buscar_reporte_demoras(request): if request.method == "GET": …

27.11.2025
Paystack integration with Django

I'm trying to integrate paystack into my django E-commerce but I keep getting this error, ❌ Order creation error: [WinError 10061] No connection could be made because the target machine actively refused it, when i try to checkout. Can anyone …

25.11.2025
My password field and confirm_password field are not being validated as expected except through my view

I am working on a practice project for a P.A.Y.E system. My layout template, home page template, navbar template are located at project level. While my registration template is at app level in my django project. I wrote code in …

25.11.2025
How do I make a custom field output different datatypes depending on file asking for data?

I'm building a molecule properties displaying website using django and sqlite. The database takes a numpy array and stores it as a BLOB. Currently, it just outputs the numpy array back out when asked for it. I'd like it to …

25.11.2025
API request tracing with NextJS, Nginx and Django

I’m trying to measure the exact time spent in each stage of my API request flow — starting from the browser, through Nginx, into Django, then the database, and back out through Django and Nginx to the client. Essentially, I …

23.11.2025
Get the data from the server with fetch API

I get the data from the server with fetch API it contains html, when i click on load more posts button it should load the html at the bottom of the page we got from the server, but it also …

23.11.2025
How should I structure a Django backend with a Vue 3 frontend for a news application?

I’m building a small “newsroom” application where Django handles the backend (API, authentication, admin) and Vue 3 handles the frontend UI. I’m still fairly new to combining Django with a modern JavaScript framework, and I’m running into questions about the …

23.11.2025
Nginx not serving static files

Hi everyone I am trying to upload a application using Nginx, Gunicorn, Django application run fine in development environment but for production it does not serves static files. I tried hard but failed to find any solution so I am …

22.11.2025
Restarting backend container became unreachable for traefik(504 Gateway timeout)

I’m having a problem and I can’t find a solution. I have deployed a Django backend and a React frontend using Docker. I’m using Traefik as a reverse proxy for the web server. When I start Traefik, the backend, and …

21.11.2025
How do I response partial html with fetch

I response posts in partials html with fetch, but each time get posts from server also return current page header. i just want to get header first. partial html(server responses it when requested with fetch) {% for post in posts …