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

03.07.2025
После попытки контеризировать приложения события Celery перестали обрабатываться [closed]

Я написал простой сайт на Django по покупке билетов, Celery когда пользователь начинает процесс оплаты места, оно бронируется. если через n секунд он все еще не оплатил - то оно освобождается с помощью Celery. когда я запускал сайт локально (поднимая …

03.07.2025
Unable to run tests django. django.db.utils.ProgrammingError: relation "auth_user" does not exist

I'm writing tests. When trying to run it, it returns the error "django.db.utils.ProgrammingError: relation "auth_user" does not exist". I'm running the project locally using a virtual environment. There is a similar error in the logs in pgadmin. This error also …

03.07.2025
Gunicorn gevent CERTIFICATE_VERIFY_FAILED error

I have a Django website running in a Docker container (Debian), which I deploy with the following command: gunicorn core.wsgi:application --bind 0.0.0.0:8000 --workers 33 --worker-class gevent --timeout 1200 I created a simple view with an outgoing …

03.07.2025
Wagtail login downgrades to http, gives error

I am setting up a new, local version of a Django Wagtail project (which I have had running locally before). I am able to see Pages in my browser, but when I try to login (on FF, Chrome, Safari-with-no-plugins) at …

03.07.2025
Django media images not loading in production using Nginx , with Debug=False

I'm deploying my Django project with DEBUG=False, and media files like images are not loading. Nginx Configuration server { listen 80; listen [::]:80; server_name <my_server_ip>; location /media/ { alias /home/ubuntu_server02/cdo_portal/media/; autoindex on; } location / { proxy_pass http://127.0.0.1:8000; …

03.07.2025
Django-mptt using get_root() on TreeQuerySet element inside for loop and output stored in list does not persist outside of for loop

I am trying to use get_root() on individual TreeQuerySet elements in a for loop. This seems to work in the Django Python shell as shown below. Upon pressing [Enter] twice to indicate the end of the for loop, the result …

03.07.2025
Why aren't my Django Postgres `ArrayAgg` members sorting?

I'm exploring the use of ArrayAgg and I don't understand why 'histidine-[13C6,15N3]' doesn't occur before 'isoleucine-[13C6,15N1]' in this example: In [25]: for i in Infusate.objects.annotate(tns=ArrayAgg("tracer_links__tracer__name", order_by="tracer_links__tracer__name")).order_by("tns").distinct(): ...: print(i.tns) ...: ['inosine-[15N4]'] ['isoleucine-[13C6,15N1]', 'leucine-[13C6,15N1]', 'valine-[13C5,15N1]'] ['isoleucine-[13C6,15N1]', 'lysine-[13C6,15N2]', 'phenylalanine-[13C9,15N1]', 'threonine-[13C4,15N1]', 'tryptophan-[13C11]', 'histidine-[13C6,15N3]'] …

02.07.2025
Django, docker compose, whitenoise and railways: new js files not found in production (it works in local)

I am working in a django project where I have installed and configured whitenoise to serve static files in railways. But railways is not serving or collecting my new js files. In my browser I get a 404 in settings …

02.07.2025
How can I display a table in a template with additional category/section rows?

Have a nice day! I have a non-standard table. Which I plan to display in the template. I load the table into the template from the model. And I have additional sections - additional fields. These additional fields characterize - …

02.07.2025
How to support multiple Google Cloud Storage buckets in a Django FileField without breaking .url resolution?

I'm using Django with django-storages and GoogleCloudStorage backend. My model has a FileField like this: raw_file_gcp = models.FileField(storage=GoogleCloudStorage(bucket_name='videos-raw')) At runtime, I copy the file to a different bucket (e.g. 'videos-retention') using the GCS Python SDK: <pre …

02.07.2025
I tried to implement custom validation error in django

I have wrote this validators.py file: from django.core.exceptions import ValidationError import os def allow_only_images_validator(value): ext = os.path.splitext(value.name)[1] print(ext) valid_extensions = ['.png', '.jpg', '.jpeg'] if not ext.lower() in valid_extensions: raise ValidationError(&quot;Unsupported file extension. Allowed extensions: &quot; +str(valid_extensions)) This is my …

02.07.2025
In Django how can I list a Queryset in one view/template generated by another view?

I'm developing a tracking system that has 2 main datasets Orders and Shipments. Focussing on Orders I want to enable users to enter any combination of field data and then display the resulting list using pagination. To achieve this I …

02.07.2025
How can I convert a QuerySet list to a list or a dataset for the choices field?

After doing some filters and operations, I write the data to the model. I get the data after processing in the model. Then I unload the data when displaying the form. There is a field in the form - which …

02.07.2025
Invoice bill creation for the specific customers in billing software django forms

I am trying to create a invoice bill for the specific customer , first on the bill customer selection should be available for the selection of the customer , after that we are giving the option to add the items …

02.07.2025
Square Webhook doesn't give confirmation if the payment is done or not to Python-django

I'm encountering a critical issue where my Django backend is unable to receive confirmation from Square about whether a payment has been completed. Here are the environment details for reference: Python: 3.13.2 Django: 5.1.6 Square SDK: 43.0.0.20250618 Problem …

01.07.2025
How to show following count in template django

I was able to get count for follower/following users, but when user A follow user B, user B accept user A follow request(they are in friends list). After accept request, I want to display count (1) for user A Follower …

01.07.2025
How can I split the two forms so that only one of the two forms in the template is processed?

I am trying to place two independent forms on one template. I have them placed but there is a problem that both forms are being checked. Validation of both forms is being checked. Although I only have one button clicked …

01.07.2025
How to apply the two dropdown selectors in django

Form.py: from django import forms from .models import Invoice, InvoiceItem # Form for the Invoice model class InvoiceForm(forms.ModelForm): class Meta: model = Invoice fields = ['customer'] labels = { 'customer': 'Select Customer', # 'total_amount': 'Total Amount', } this above …

30.06.2025
How do I log filtered GET requests on a Django REST Framework ModelViewSet using @action?

I have a ModelViewSet for EventReportLink and need to log every time someone queries with ?event_report__id=&lt;id&gt;. I’ve tried adding a custom @action(detail=False, methods=['get']), but I’m not sure if I’m implementing it correctly or if there’s a better way. I added: …

30.06.2025
How to remove hardcoded library version info from minified JS files in Django production?

'm using Django to serve static files in production, and I've noticed that many of the third-party JS libraries (like jQuery, Bootstrap, JSZip, and Moment.js) include hardcoded version numbers inside the minified files. For example: /*! jQuery v3.3.1 */ &quot;version&quot;: …

30.06.2025
Медленно работает форма Django

Создал форму через forms.ModelForm в django, на форме есть выпадающий список с очень большой выборкой из таблицы (список производителей запчастей, foreign key). Форма очень медленно работает, можно ли как-то это оптимизировать? В админской панели есть autocomplete, а как его на …

29.06.2025
How to integrate ZKTeco ZK4500 fingerprint scanner with a Django + React web application? [closed]

I'm working on a web application using Django (backend) and React (frontend), and I want to integrate the ZKTeco ZK4500 fingerprint scanner into my system for user authentication. 🔍 My Setup: Device: ZKTeco ZK4500 (USB fingerprint scanner) Backend: Django …

29.06.2025
Filter some data in one column in table

In a Django project, I want to display values from a table in the database, provided that a filter is applied to some data in one of the columns. For example, the gender column. I want to display only female …

28.06.2025
How to handle constraint errors like unique or not null from DB in Django

I have a write operation which adds a record in rider model. The rider_code is unique in this. Now 1 way is to first check if any record with that rider_code exists then return error else create rider. But it …

27.06.2025
Django application deployement with Docker

I am trying to deploy my django app with docker. But when it come to excute my script to be sure that the databse (postgres) is ready, I allways get this error : chmod: /app/scripts/wait-for-it.sh: Permission denied and then the …

27.06.2025
Celery is not running despite correct configuration - using Django, Celery 5+, and Python 3.12+

Despite what appears to be a correct initial configuration, Celery tasks are not running. The logging system does not show any errors. This is a new setup of Celery version 5+ running on Python 3.12+. Full server-side configuration has been …

27.06.2025
How to make DRF use url path as empty and base path?

I am trying to omit the URL path for an action in a ViewSet like @action(detail=False, methods=['patch'], url_path='') def update_current_user(self, request): But when I give url_path as an empty string, DRF defaults to the function name and looks for …

27.06.2025
ImportError: Module "django_comments_xtd" does not define a "XtdComment" attribute/class

When I installed django-comments-xtd according the documention I got this error: ImportError: Module &quot;django_comments_xtd&quot; does not define a &quot;XtdComment&quot; attribute/class Configs in settings.py are: INSTALLED_APPS += [ 'django_comments_xtd', 'django_comments', 'django.contrib.sites', ] SITE_ID = 1 COMMENTS_APP = …

26.06.2025
Django forloop in template

Forloop is overriding the other, how do I use two different forloop in one template without interrupting each other. The 'include template&quot; do not display its contents if 'for users in all_users' is the parents. How do I make 'for …

26.06.2025
ERROR: Failed to build installable wheels for some pyproject.toml based projects (mysqlclient)

Building wheel for mysqlclient (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for mysqlclient (pyproject.toml) did not run successfully. │ exit code: 1 ╰─&gt; [91 lines of output] C:\Users\Acer\AppData\Local\Temp\pip-build-env-qm2za2yg\overlay\Lib\site-packages\setuptools\config_apply_pyprojecttoml.py:82: SetuptoolsDeprecationWarning: project.license as a TOML table is deprecated !! ******************************************************************************** …

26.06.2025
How can I filter values ​from one model and insert the result into the form as choices?

Good day! I have two tables - models. I fill them gradually. First I have the first table. First I enter data into the first table. And there - in the first table I have - repeating data. Field - …

26.06.2025
Elasticsearch search only by one field

I have app on drf and i added elasticsearch(django_elasticsearch_dsl) for searching. But i faced with problem, when i want to search on two or more fields, elastic searching only by one field. I'm trying to search by both 'title' and …

26.06.2025
Add new input field to Django form

I am working on a signup form within a Django project. I have the following: &lt;div class=&quot;form-row&quot;&gt; &lt;div class=&quot;col-md-6&quot;&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;label class=&quot;large mb-1&quot;&gt;First Name&lt;/label&gt; {{ form.first_name }} &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-md-6&quot;&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;label class=&quot;large mb-1&quot;&gt;Last Name&lt;/label&gt; …

25.06.2025
Why are we seeing incorrect timings in Datadog APM tracing for simple actions like a Redis GET?

We have Python Django application deployed to AWS EKS on EC2 instances. We use Gunicorn as our web server, although we recently ran Apache + wsgi and saw the same issues. The EC2 instances are m6a.xlarges, the containers themselves have …

25.06.2025
Deploying Django + xlwings library

I'm trying to deploy a Django app which uses the xlwings dependency (windows only) on a server. Tried on Linux, but it does not support xlwings. So, now looking out for an easy way to set up the Deployment with …

25.06.2025
How can I create a table or form with the addition of values from another table based on the selected values?

Good day! I have several model tables. And each subsequent table in the conditional hierarchy is one step lower than the previous one. I have one model that is planned to be filled from the form in the database. And …

25.06.2025
Can I use my DjangoCMS template in my AppHook application?

Context: I am trying to integrate an application in my djangocms website. As i want it seems totally integrated, i want my appHooked application to use the same template as my main DjangoCMS template (I am using an extends of …

25.06.2025
Cloudinary image upload isssu with python, Django and DRF

I am trying to upload my produts image to cloudinay, I setting all thing correctly adding middleware but always my image saevd in locally

25.06.2025
How to update removed model choices in Django without breaking existing database values?

I'm working on a Django project where we use models.TextChoices for fields like current_status. Our client requested wording updates — for example, renaming &quot;Contacted&quot; to &quot;Contacted for assessment&quot;, &quot;Booked&quot; to &quot;Assessment booked&quot;, and so on. Previous Enum: class …

24.06.2025
React doesn’t receive API tokens after Google OAuth redirect via social_django/drf-social-oauth2

I'm implementing Google OAuth2 for my Django REST API with a React frontend. The basic flow is set up correctly. I have routes for: urlpatterns = [ path(&quot;admin/&quot;, admin.site.urls), path(&quot;api/v1/&quot;, include((v1_patterns, &quot;v1&quot;))), path(&quot;api/v1/auth/&quot;, include(&quot;social_django.urls&quot;, namespace=&quot;social&quot;)), path(&quot;api/v1/auth/token/&quot;, include(&quot;drf_social_oauth2.urls&quot;, namespace=&quot;oauth2&quot;)), …