"Вопросы и ответы" Django и Python, страница 2

22.03.2025
Как передать значение pk в формы и правильно вызвать метод view.py, показывающий модальное окно подтверждения в django

<<0>>>Проблема в том, что я не вижу никаких сообщений печати или журнала в моем views.py, что привело меня к выводу, что этот метод не вызывается.<<<1>>> < <<0>>>Я хочу отменить подписку клиента с помощью кнопки и показать модальное окно …

22.03.2025
Миграция моделей Django генерируется после установки значения False для managed

<<0>>>В моем проекте django модели Form, FormSubmission, CmsEvent находятся в базе данных postgres, а модели CmsEventOrder, CmsEventPayment - в другой базе данных postgres.<<<1>>> < <<0>>>Когда я создаю миграции, миграции создаются для всех моделей, в то время как они …

22.03.2025
HTTP FAILED: java.net.ConnectException: Не удалось подключиться к /127.0.0.1:8000

<<0>>>Я Kotlin разрабатываю Django приложение для android в <<<1>>> и пытаюсь сделать запрос к моему локальному <<<2>>> серверу, но получаю эту ошибку.<<<3>>> < <<0>>>Локальный 127.0.0.1:8000 сервер http://127.0.0.1:8000/api запущен на IP и порту <<<1>>> и я указал в своем …

22.03.2025
Иерархия объектов «один к одному» с полем типа enum

У меня есть сайт wagtail, и я хочу создать иерархию объектов по принципу «один к одному», но с несколькими вариантами. В принципе, я хочу, чтобы настройка базы данных выглядела следующим образом: CREATE TABLE products ( id PRIMARY KEY, product_type …

22.03.2025
Аутентификация Azure AD с Django на AWS ALB: проблема с перенаправлением URI

Я пытаюсь интегрировать аутентификацию Microsoft в мое приложение Django, используя пакет django_auth_adfs. Однако я столкнулся с ошибкой, связанной с несоответствием URI перенаправления. Я следовал документации, предоставленной django_auth_adfs для настройки интеграции Azure Active Directory. На портале Azure я …

21.03.2025
Как придать стиль ярлыку Django crispy-form

Я разрабатываю небольшой проект, используя Django v5 и Bootstrap v5. На данном этапе я просто играю со страницами registration и login, но я хотел бы стилизовать форму, используя crispy-form и crispy FormHelper. Я могу изменить отображаемую метку, но (пока) …

21.03.2025
Невозможно аутентифицировать пользователя Django с помощью электронной почты вместо имени пользователя

Я пытаюсь реализовать в Django аутентификацию по электронной почте вместо использования имени пользователя по умолчанию. Я обновил модель пользователя и бэкенд аутентификации, но все еще не могу аутентифицировать пользователей по их адресам электронной почты. views.py from django.shortcuts import render,HttpResponseRedirect …

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 alt="this …

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() "/home/&lt;user&gt;/&lt;projects&gt;/static/css/custom.css" failed (13: Permission denied), client: ip, server: domain, request: "GET /static/css/custom.css HTTP/1.1", host: "domain", referrer: "http://domain/" 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 …

20.03.2025
Django session cookies not persisting

I have a Django API which upon successful login, uses the Set-Cookie Response Headers to set a sessionId and CSRF Token in the cookies. I had it working and all of a sudden it stopped, the cookies no longer persist. …

20.03.2025
404 error on Python App deployment on CPanel

Python==3.11.11 (server ver) Django==5.1.1 Hello, today I was to deploy my app on CPanel, and everything goes fine until the end, because when configurations are all done, the page put an 404 error: Not Found The requested URL was not …

20.03.2025
What is the best way to have row-level authorization in django with some constraints?

I have a django app which consists of multiple different models. These models are related to each others with database relations. And somehow these relations are making a hierarchy. For example: Model City can have multiple Libraries Model Library can …

20.03.2025
Create a Django custom Transform from an annotation

I've got an annotation for a foreign key field that I use frequently and would like to write a custom Django Transform which behaves similar to the annotation. The annotation that does what I would like is in this snippet: …

19.03.2025
Why does duplicating a Django filter condition change PostgreSQL’s query plan estimates?

I'm working on a Django project with PostgreSQL and have implemented a custom filter to select "active" records. The filter is defined as follows: def get_custom_filter(qs): return qs.filter( Q( Q(timestamp_field__lte=timezone.now(), related_obj__delay__isnull=True) | Q( related_obj__delay__lte=timezone.now(), type_obj__flag=False, timestamp_field__isnull=False, ) | Q(type_obj__flag=True, timestamp_field__lte=timezone.now()) …

19.03.2025
Why does my uwsgi app respond with prematurely closed connection?

I can serve my django app running uwsgi --socket lhhs/lhhs.sock --module lhhs/lhhs.wsgi --chmod-socket=664 And the django app runs quick and running python manage.py test shows it is fine. But uisng nginx and uwsgi-emperor I get upstream prematurely closed connection while …

19.03.2025
Django/CKEditor - config for extraProviders

How can I configure a simple extraProvider for local media in my CKEDITOR_5_CONFIGS in the settings.py file? I tested the configuration below via javascript and it worked fine, but when I switched to python, I got the error Uncaught CKEditorError: …

19.03.2025
I can't solve the migration problem in django

I put the oracle db that I was currently developing with django and oracle into the db that impdp and distributed it. However, the distribution db has a different schema name from the development db, so it is not possible …

19.03.2025
Deploy logs "--error-logfile/--log-file" railway with django

I'm deploying my django app for the very first time on railway. On railways in the project deployment details I see: enter image description here However when I go in the deploy logs I see this error …

19.03.2025
Error when applying migrations 'no password supplied', but I can connect to the database from the interpreter

I decided to revive my pet project that I wrote 2 years ago. First I had to update all dependencies, this is ok. But migrations are not performed when working with a local server. The pg_hba.conf file has md5. At …

19.03.2025
Как в Django Rest Framework перенести router.regiter() в декоратор

Написал декоратор который будет регестрировать в переданный router Viewset def register(router, prefix, basename=None): def decorator(viewset): if not prefix: raise ValueError('Не указано имя Viewset') if not issubclass(viewset, viewsets.GenericViewSet): raise ValueError('Wrapped class must subclass GenericViewSet.') router.register(prefix, viewset, basename) return viewset return decorator …

19.03.2025
Is there a way to define an authentication for webhooks in DRF Specacular

I have the following webhook definition change_event_webhook = OpenApiWebhook( name="AddonWebhook", decorator=extend_schema( summary="A Webhook event", description="Pushes events to a notification URL. ", tags=["webhooks"], request={"application/json": load_schema("myschema.json")}, responses={ "2XX": OpenApiResponse("Event was received successfully"), }, ), ) which produces the following …

19.03.2025
How to Automatically Copy Product Attributes to Variants in Django Models?

I am building an e-commerce website in Django where: A Product can have multiple variants. Each product has attributes (e.g., color, storage, display size). I want each variant to automatically inherit all attributes from the main product when it …

19.03.2025
Programmin Error at Routes , i am not getting why is the happening , please help me?

ProgrammingError at /routes/ column airline_app_route.route_id does not exist LINE 1: SELECT "airline_app_route"."route_id", "airline_app_route"."... ^ Request Method: GET Request URL: http://127.0.0.1:8000/routes/ Django Version: 5.1.7 Exception Type: ProgrammingError Exception Value: column airline_app_route.route_id does not exist LINE 1: SELECT "airline_app_route"."route_id", …

19.03.2025
How to cache python pip requirements of docker build progress?

I'm on a very slow internet connection, and the RUN pip install -r requirements.txt step of docker compose up --build keeps timing out halfway through. When I run docker compose up --build again, it looks like it restarts from …