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

24.03.2025
Using pghistory with custom event table names

I'm currently testing pghistory for our Django project. I set up a few models to be tracked. As a convention our model names are different from the actual table names - these are defined in the Meta class like so: …

24.03.2025
How to use multiple database connections in Django TestCase

I'm writing a testcase to reproduce deadlock in my service. After I use multiprocessing to create a two thread, I found they use the same database connection. So I can't reproduce the deadlock scenario in testcase. How do i resolve …

24.03.2025
Unable to Import 'celery' When Running pylint, but Django Runs Fine

I am working on a Django project and using uv as the package manager. My dependencies are managed in pyproject.toml, and I have the following setup: pyproject.toml (Relevant Parts) [project] name = "port-backend" version = "0.1.0" description = "Backend service …

24.03.2025
TemplateSyntaxError : Could not parse the remainder

Using easy-thumbnails package. Getting the error for the template file below. Cant seem to figure out what the syntax issue is. i.image is of type ImageFileField **Could not parse the remainder: ' i.image 320x260' from 'thumbnail i.image 320x260' ** …

23.03.2025
/bin/bash: line 1: gunicorn: command not found in railway

I am trying to host the Django backend of my website on railway, however when I try and deploy the server, I get: /bin/bash: line 1: gunicorn: command not found error in logs I've followed all the steps of creating …

23.03.2025
How to design a Django database schema for tracking user-item interactions (with quantities) to enable analytics and reporting?"

I'm building a Django web app to manage item stock, where authenticated users can "take" items from inventory (I'm not using djangos authentication system, is more like the user enters a code and the app checks in SQL Server if …

23.03.2025
Other users cannot connect to the server on the websocket

I have a server on AWS EC2 with port 8001 open with a websocket application. The application itself is written in Django Channels and uses a daphne server. The problem is that I myself can connect to the websocket server, …

23.03.2025
How to parse api request to defined model?

I'm new with python, I'm trying to parse api request to a defined model, so how to fix below code? class PersonSerializer(serializers.Serializer): name = serializers.CharField() class APIJustTest(APIView): parser_classes = (JSONParser,) @swagger_auto_schema(request_body=PersonSerializer) def post(self, request, *args, **krgs): serializer = PersonSerializer(data=request.data) serializer.is_valid() …

23.03.2025
Cannot assign "": "" must be a "User" instance

I'm making a project using the Django framework and is creating a website and is encountering this error: Cannot assign "<User: >": "Booking.teacher" must be a "User" instance. this is my model for User: class User(AbstractUser): groups = …

23.03.2025
Django template nested for loop from 2 different lists

I have 2 lists (if that is what django calls them) containg an id and a key/value pair e.g. [{'id': x, 'string': 'string'}] one list assigned to variable 'periods' the other assigned to 'paydates'. I am trying to loop through …

23.03.2025
Adding HTTPS to django app on VM(Windows OS) Production level

We are developing react native app with django as a backend. We deployed django on VM(which we bought it has Window OS) and there git pulled and running django server by just uvicorn backend.asgi:application --host 0.0.0.0 --port 8000, we want …

23.03.2025
Run one time for Django model calculated property

Class Company_Car(models.Model): @property def days_left(self): print("RUNNED PROPERTY") if self.date_valid is not None and self.date_valid >= datetime.datetime.now().date(): return (self.date_valid - datetime.datetime.now().date()).days added = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) company = models.ForeignKey(Company, on_delete=models.DO_NOTHING) date_valid = models.DateField(null=True, blank=True) Each time when i ask …

23.03.2025
Django: How to dynamically update stock quantity when selecting a product variation?

I am working on an e-commerce project where a product has multiple variations (like different colors, sizes, etc.), and each variation has its own stock. When a user selects a variation, I want to update the displayed stock dynamically, but …

23.03.2025
Is there any way to serve a Django application using preload, ASGI, and SO_REUSEPORT?

I can't find a way to serve our large Django application using all three of preload, ASGI, and SO_REUSEPORT. Without preload and fork we use much more memory (gigabytes). Without ASGI we can't serve websockets (and starting another server just …

23.03.2025
Should I Serve a React Build with Django or Use a Node.js Server if I am using Websockets with Django Channels?

I have a React application that I need to deploy, and I am considering two options for serving the production build: 1. Serving the React build directly with Django (e.g., using WhiteNoise or serving it as static files). 2. Using …

22.03.2025
How to pass pk value in the forms and correctly call view.py method , showing a confirmation modal in django

The problem is that i dont see any print or log messages in my views.py , which made me to a conclusion that that method is not method is not being called. What i want to is to cancel subscription …

22.03.2025
Django models migration gets generated after managed set to False

In my django project, the models Form, FormSubmission, CmsEvent are in a postgres database and the models CmsEventOrder, CmsEventPayment are in another postgres database. When I makemigrations, the migrations is created for all the models, while it should only be …

22.03.2025
HTTP FAILED: java.net.ConnectException: Failed to connect to /127.0.0.1:8000

I am developing an android app in Kotlin and trying to make a request to my local Django server but getting this error. The local server is launched on IP and port 127.0.0.1:8000 and I specified in my android application …

22.03.2025
Wagtail one-to-one object hierarchy with enum type field

I have a wagtail site and I want to create an object hierarchy in a one-to-one matter, but with multiple options. Basically, I want that the database setup look slike this: CREATE TABLE products ( id PRIMARY KEY, product_type VARCHAR(10) …

22.03.2025
Azure AD Authentication with Django on AWS ALB: Redirect URI problem

I am trying to integrate Microsoft authentication with my Django app using the django_auth_adfs package. However, I encountered an error regarding a mismatch in the redirect URI. I have followed the documentation provided by django_auth_adfs for configuring …

21.03.2025
How to style a Django crispy-form label

I'm developing a small project using Django v5 and Bootstrap v5. At this stage I'm just playing around with the registration and login pages but I'd like to style the form using crispy-form and the crispy FormHelper. I can change …

21.03.2025
Unable to authenticate Django user with email instead of username

I'm trying to implement email-based authentication in Django instead of using the default username. I’ve updated my User model and authentication backend, but I’m still unable to authenticate users with their email addresses. views.py from django.shortcuts import render,HttpResponseRedirect from .forms …

21.03.2025
Как выполнить условие {% if %}

Необходимо что бы во вкладке отображались данные по направлениям при написании {% if n.route == "ЦДНГ-2,ДНС-1,ЦДНГ-1,ДНС-1" %} условие не выполняется что я делаю не так <div class="panel_data"> <div class="tab"> {% …

21.03.2025
Django: ORM player substitution, checking __isnull=False versus is not None

I have a Django model Player. Now this model has a save method which goes like this: def save(self, *args, **kwargs): """ Overrides the save method to convert the 'name' attribute to uppercase before saving. """ player = Player.objects.filter( Q(fide_id=self.fide_id, …

21.03.2025
How does one correctly define an index for efficiently querying the reverse relation for ForeignKey fields? (Django)

So I've spent days searching on and off for an answer to this question, and much to my surprise, I can't seem to find anbyone asking this specific question, nor any mentions of the confusion I have around it. My …

21.03.2025
Configuring wagtail-markdown to use Prism instead of Pygments

Is there a way to inject a class into the <code> tag produced by wagtail-markdown so that I can style my Markdown code blocks with Prism instead of Pygments, which is …

21.03.2025
Accessing a foreign key's base classes's fields in UniqueConstraint

In the UniqueConstraint for personality -> language, I'm getting the error FieldDoesNotExist For example, if my code looked like this: class LanguageModel(models.Model): language = models.CharField( max_length=16, default="en", ) class Meta: abstract = True class PersonModel(LanguageModel): created_at = models.DateTimeField(editable=False, …

21.03.2025
ValueError: The field exam.Question.created_by was declared with a lazy reference to 'add_user.user', but app 'add_user' isn't installed

This error keeps appearing, even though I have the add_user app installed in my directory and registered in the settings.py file.

21.03.2025
PyCharm 2024. 3.5 Django docker compose set project path in container

I have a docker compose Django project that runs fine in a terminal on the server and I'm trying to set up PyCharm for development debugging. In my docker-compose.py I have a volume mapping the project root on the host …

21.03.2025
Got multiple values for argument 'request' in get_user_colls method of Django Ninja Extra

I'm using Django Ninja Extra to write an API controller. Here is my code: @api_controller('', tags=['User'], auth=NOT_SET, permissions=[]) class User: @http_get('/user/colls', response=List[schemas.UserCollsOut], auth=JWTAuth()) @paginate(PageNumberPagination, page_size=10) def get_user_colls(self, request): data = userModels.UserCollection.objects.filter(user=request.auth) return data When I run this code, I …

21.03.2025
My django app ORM is not working properly [closed]

I had my project set up on my local computer, and in the beginning, everything was working file. for past couple of days. my django ORM is not working properly it showing failed SQL error <img src="https://i.sstatic.net/pBiQAp4f.png" …

21.03.2025
Ubuntu server with Django, Gunicorn, Nginx does not give static

The file /var/log/nginx/error.log contains errors of the following type: [error] 714#714: *5 open() &quot;/home/&lt;user&gt;/&lt;projects&gt;/static/css/custom.css&quot; failed (13: Permission denied), client: ip, server: domain, request: &quot;GET /static/css/custom.css HTTP/1.1&quot;, host: &quot;domain&quot;, referrer: &quot;http://domain/&quot; The following settings are specified in the /etc/nginx/sites-available/&lt;project&gt; file: …

21.03.2025
Сервер на Ubuntu с Django, Gunicorn, Nginx не отдает статику

В файле /var/log/nginx/error.log ошибки следующего типа: [error] 714#714: *5 open() &quot;/home/&lt;user&gt;/&lt;projects&gt;/static/css/custom.css&quot; failed (13: Permission denied), client: ip, server: domain, request: &quot;GET /static/css/custom.css HTTP/1.1&quot;, host: &quot;domain&quot;, referrer: &quot;http://domain/&quot; В файле /etc/nginx/sites-available/&lt;project&gt; указаны следующие настройки: server { listen 80; server_name &lt;domain&gt;; …

20.03.2025
Django same slug but using different URL path

I am making a documentation site to self-host for myself; learning Django at the same time. I am at the point where I am starting to populate the website. I am wondering if there is a possibility to have two …

20.03.2025
I can develop a bulk massge software [closed]

How can I develop software that allows me to send bulk messages to customers via WhatsApp by importing a CSV file, using the official WhatsApp API, ensuring that my account remains active and does not get blocked? I need guidance …

20.03.2025
As django fresher developer what sequence of topics need to be done? [closed]

Please elaborate it I tried learning it with some tutorials of youtube, but not clear like its enough or not. I currently worked on shells, migrations, authentication and everything I need to do. I wanna land a good job as …

20.03.2025
How can I change device creation to be managed only through the Client model, and restrict direct device creation? [closed]

I currently have a system where devices can be created and managed through the Device model directly. However, I want to change it so that devices can only be added or deleted through the Client model, and not directly through …

20.03.2025
Hosting a web in local server

I built web with django, and hosted it in heroku. Now I am working for a bank and going to build dashboard, but I can not host it on heroku. It should be in the local server only as far …

20.03.2025
Form submit confirmation does not work in jQuery `ready()`

Working in Django, I am trying to update the items of a database through submitting a form. I need a confirmation dialog before submission. These are my lines on related code: $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'GET', url: 'http://127.0.0.1:8000/update_in_line_orders', success: function(response){ …

20.03.2025
Gemini 2.0 experimental image generation in django

I am working on a webapp with django backend. It is related to image generation with character consistency, we finally have a model that works well for that, gemini 2.0 flash experimental. I am generating a character with openAI and …