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

27.12.2025
Django ManyToMany self relationship with through model — user_from and user_to reversed behavior

I added following and followers by using intermediate model, it`s ok but does not correctly specify objects in the intermediate model. I expect the user who follows must to be in the user_from field and the one who followed to …

26.12.2025
Unsupported operand type(s) for +: 'NoneType' and 'datetime.timedelta'

I'm getting the above error while executing the following method in my django rest framework project (Django==5.0.4, djangorestframework==3.16.1). def activate( self, subscription_date=None, mark_transaction_paid=True, no_multiple_subscription=False, del_multiple_subscription=False, ): if no_multiple_subscription: self.deactivate_previous_subscriptions(del_multiple_subscription=del_multiple_subscription) current_date = subscription_date or timezone.now() next_billing_date = self.plan_cost.next_billing_datetime(current_date) self.active = …

26.12.2025
LinkedIn organizationPageStatistics API returns 400 PARAM_INVALID for timeIntervals (REST.li 2.0)

I am calling the LinkedIn organizationPageStatistics endpoint using the REST.li 2.0 API, but I keep getting a 400 PARAM_INVALID error related to the timeIntervals parameter. According to the official documentation (li-lms-2025-11), timeIntervals is an object, not a list. Error response …

26.12.2025
Which one is best for 2026 Python developers , Python Data science or Python Django?

Only Experts Can Answer this question. Which one is best for 2026 Python developers , Python Data science or Python Django? From both of these which one is easy to learn and high paid?

24.12.2025
Research survey: Evaluating Code First vs Database First in different ORMs

I am conducting an academic research study focused on comparing Code First (CF) and Database First (DBF) approaches in different ORMs. The goal of this survey is to collect objective, experience-based input from developers who have worked in real-world projects. …

24.12.2025
Почему выдает ошибку в django model?

Выдает такую вот ошибку, в чем дело? RuntimeWarning: Accessing the database during app initialization is discouraged. To fix this warning, avoid executing queries in AppConfig.ready() or when your app modules are imported. warnings.warn(self.APPS_NOT_READY_WARNING_MSG, category=RuntimeWarning) вот мой код в файле models.py: …

23.12.2025
Django DRF JWT Authentication credentials were not provided on UpdateAPIView even for is_staff user

I'm implementing JWT authentication using Django REST Framework and djangorestframework-simplejwt in my project. I have an endpoint for updating a category. What I tried Verified that the JWT token is valid. Confirmed that the user is is_staff=True and …

23.12.2025
What does _db used for in a django Model Manager

While trying to create a custom QuerySet and a custom Manager for a django Model I stumbled upon the documentation sections 1 and 2 that use the manager's _db property and i would like …

23.12.2025
Gunicorn (Uvicorn Worker) continues processing requests after Heroku 30s timeout

I’m running a Django (ASGI) app on Heroku using Gunicorn with the Uvicorn worker to support WebSockets. Heroku has a hard 30-second request timeout. When a request exceeds 30 seconds, Heroku closes the connection as expected. Problem: Even after the …

21.12.2025
Correct implementation of Wright–Malécot inbreeding coefficient using shortest paths (Python/Django)

I am implementing the Wright inbreeding coefficient (F) for individuals in a pigeon pedigree (Django application, relational database). The current implementation builds the pedigree using a breadth-first search (BFS) up to a fixed number of generations and computes F using …

21.12.2025
Existing Django project on Pythonanywhere refuses to correctly use static? [closed]

I have done the guide and yet i still cannot get it to work correctly. These two screenshots are the closest i have come to success attempt1 attempt2 This is how …

21.12.2025
Does using Django model choices for search filters add server load on every page request?

I’m building a Django-based classifieds website. Previously, my search form populated districts and categories using database queries like: districts = ( AdPost.objects .filter(admin_verified=True) .values_list("district", flat=True) .distinct() ) To improve consistency and performance, I’ve now moved both district and category to …

20.12.2025
Change color for StackedInline?

I'd like to change background color for these headers for different color (not white): Like this: My models: from django.core.validators import MinValueValidator, MaxValueValidator from django.db import …

19.12.2025
How to do nested inlines in Django?

I have models: from django.db import models class Request(models.Model): class Method(models.TextChoices): POST = "POST", "POST" GET = "GET", "GET" PUT = "PUT", "PUT" DELETE = "DELETE", "DELETE" method = models.CharField( max_length=10, choices=Method, default=Method.GET, ) url = models.TextField() class Response(models.Model): request …

19.12.2025
How to make different url aliases work for local django development

I am using django-tenants and created various aliases that all point to localhost. If the local development server is reachable via http://localhost:8000/ and I can login to the admin as expected. If I use e.g. http://other_url.local:8000/django-admin the …

18.12.2025
Django Can't find table during insert: LINE 1: SELECT 1 AS "a" FROM "qmgr_def_rules" WHERE "qmgr_def_rules"

I'm trying to add a row to my model, but it keeps coming back with: django.db.utils.ProgrammingError: relation "qmgr_def_rules" does not exist LINE 1: SELECT 1 AS "a" FROM "qmgr_def_rules" WHERE "qmgr_def_rules"... Some context: I have 3 different applications under …

18.12.2025
Django admin update get_queryset only for "change" view

In my django project admin I have an Order model. I display a bunch of information in the change page with the help of custom inlines. As I use a lot of related models, I want to …

18.12.2025
Why does Django Http404 return a JSON payload while all other Http error responses don't?

Django's http response.py library provides an Http404 class that can be used to raise a "not found" exception which returns a 404 along with the following JSON payload: {"detail":"Not found."}. However there are no other HTTP error response classes that …

17.12.2025
Dealing with m2m changes in Django on object save

So I'm building a webhook functionality for a particular Django model, as in I trigger the webhooks for 2 events. One is for creation and one for modification, as in I wanna trigger them everytime an object of that model …

17.12.2025
How to make django textfield required

I'm somehow unable to make the field required, setting null and blank to True has no effect. # models.py from django.db import models class ExampleModel(models.Model): text_field = models.TextField() # tests.py from django.test import TestCase from .models import ExampleModel …

17.12.2025
How to insert single <li>? [closed]

I am trying to handle multi-level menu with AlpineJS. Is it posible to insert single &lt;ul&gt; (or &lt;/li&gt;) in the code below? &lt;template x-if=&quot;item.has_children&quot;&gt; &lt;!-- insert &lt;ul&gt; here--&gt; &lt;/template&gt; &lt;template x-if=&quot;! item.has_children&quot;&gt; &lt;!-- insert &lt;/li&gt; here--&gt; &lt;/template&gt;

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 &quot;python3 manage.py migrate&quot; 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(&quot;MOUNT_MEDIA&quot;): MEDIA_ROOT = &quot;/app/media&quot; print(&quot;Using Railway mounted volume for MEDIA_ROOT&quot;) else: MEDIA_ROOT = BASE_DIR / &quot;media&quot; print(&quot;Using local folder for MEDIA_ROOT&quot;) MEDIA_URL = &quot;/media/&quot; 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=&quot;seller_buyables&quot;,on_delete=models.CASCADE, null=True) buyable = models.ForeignKey(Buyable,on_delete=models.CASCADE,null=True,related_name=&quot;seller_buyables&quot;,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 располагается между скобок " (' ',) ", как исправить?

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

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 &quot;/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/db/backends/base/base.py&quot;, line 279, in ensure_connection self.connect() File &quot;/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/utils/asyncio.py&quot;, 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 …