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

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 …

21.11.2025
I can't load my CSS login page in Django admin

I have a Django project that I deployed without really adding any styling for 2 reasons: I didn't know any front-end back then. I wanted to do it for the sake of doing it. Now, I …

21.11.2025
Django: Separate session expiry times for "normal" website and admin area

It would be nice if there were an easy way to define separate session expiry time for the admin area of a django website. So, admin users could log themselves into the "normal" website (seen by all users) but when …

20.11.2025
Unable to make changes on DB or admin after crud operation./formset

I am building a mid-level project called School-Admin Panel with Django. I have completed most of the segments sucessfully, but I am having an issue with the performance forest. The formset loads and displays correctly in the browser, but after …

20.11.2025
Django Strategies for processing large datasets from an external API without a local replica table [closed]

I am building an SMS gateway system in Django that acts as an interface between university data sources (e.g., student information systems) and an SMS provider. The Architecture: To ensure data freshness and avoid redundancy, we decided not to maintain …

19.11.2025
Inject an image with the other info in the response body in djangorestframework

Hy i really need to send an image within the Response object of the djangorestframework endpoint . if there is anyone know how please take a moment and send a comment. Take into consideration not just the image will be …

19.11.2025
Displaying related items in an inline formset in Django

I have an inline formset in Django. I have a table called SubItem which is related to Item. Many SubItems to one Item. Some Items don't have any SubItems. Sections of code are obviously missing from below. The issue I …

19.11.2025
How do I make reusable HTML elements in a Django project?

I'm new to Django, and I'm working on a project where I'm reusing static pages and changing them to be suitable Django templates. As a part of the previous project, I made some custom HTML elements using JavaScript files and …

18.11.2025
Django channels tutorial issue

As I am following the Django channels tutorial (here is the link: https://channels.readthedocs.io/en/latest/tutorial/part_2.html ), I won't post any code except the specific problem I am having. In my code for the chat/routing.py, I have: from django.urls …

17.11.2025
Ajax request in django

I implemented the post like feature using ajax in the Django project, but it doesn't work. And it gives a 404 error in the console. template.html <script> $(document).ready(function(){ $(".line-button").click(function(){ var post_id = $(this).closest("post").data("post-id"); var button = $(button); $.ajax({ type: 'POST', …

17.11.2025
Python Django Rest Framework

What is the difference between decorator @api_view and @csrf_exempt in project level django rest framework? I need the difference and which is better to develop the project.

17.11.2025
Django Summernote: How to delete attachment files from server when removing them from admin?

When I delete a file from the Attachment model (which is provided by django-summernote), the record is removed from the database, but the actual file remains on the server. I want to make sure that whenever an attachment is deleted, …