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

21.02.2025
Drf use social auth with simple-jwt library AttributeError: Manager isn't available

I try to customize drf_social_oauth2 with drf simple-jwt I use core.models instead of standard social_oauth2 models, but got 500 status code, error "AttributeError: Manager isn't available; 'oauth2_provider.Application' has been swapped for 'core.Application'" My files: settings.py INSTALLED_APPS = [ ... 'oauth2_provider', …

21.02.2025
Django Formset Nested Structure Not Posting Correctly for Dynamic Fields

I’m working on a Django nested formset where users can: Add multiple colors to a product. For each color, add multiple sizes dynamically using JavaScript. Each size should have its own size_name, stock, and price_increment field. …

21.02.2025
How to implementing pagination for Django 5 admin sidebar filters?

The Problem Django's admin sidebar filters show all options without pagination, which becomes unwieldy when you have hundreds of related objects: By Study • All • Study-001: Genetic markers in mice • Study-002: Effects of caffeine ... • Study-999: Soil …

21.02.2025
CSS File not loading in Django [closed]

I have the style.css in the root static folder. When I browse the page or the css file directly in browser, it shows a 404 error. This the folder structure: …

21.02.2025
How to disable Django Debug Toolbar while rendering a template?

I'm using Django Debug Toolbar in my development environment, and it's been very helpful for debugging. However, I want to disable it when rendering a specific template. Is there a way to conditionally disable the debug toolbar for certain views …

21.02.2025
Django Formset Dynamic Add/Remove Not Working for Colors, Sizes, and Images

Problem Statement I am working on a Django formset where users can dynamically add/remove colors, sizes, and images when adding a product. The structure of my formset is as follows: A product can have multiple colors. Each color can …

21.02.2025
Is it correct to modify `django.db.connections.databases` dynamically to multiple databases? Or is it better to deploy a separate API per client?

This is my first time developing a multi-tenant SaaS application in Django, in this SaaS each company has its own PostgreSQL database, and these databases are created dynamically when a company registers. I cannot predefine all databases in settings.DATABASES, as …

20.02.2025
Handle auth workflow with django API and react

I have a frontend app written in react I have a backend application which is a django server. On top of that I am working with a 3rd party True Layer (Open Banking API) The first thing I want to …

20.02.2025
Does Django automatically recognize registration/login.html as the login template?

Does Django automatically recognize templates/registration/login.html as the login page? I'm working on a Django project and want to use Django's built-in authentication system for user login. I didn't set path to /login in urls.py but it's working on url/accounts/login/?next=/. My …

20.02.2025
Django WSGI and ASGI

How can I run the ASGI and WSGI protocols separately in my Django project? This is my project structure. . ├── chat # <== my app name │ ├── apps.py │ ├── consumers.py │ ├── __init__.py │ ├── migrations │ …

20.02.2025
Split data of an Ajax call to multiple div in Django

I have this ajax call $.ajaxSetup({ data: {txtSearch: $('#txtSearch').val(), prefilter: $('#prefilter').val(),csrfmiddlewaretoken: '{{ csrf_token }}' },}); $.ajax({ type: "POST", url: "article-filter2/", success: function (data) { $("#div_tab_search_results_contact").html(data.html_table); // working $("#div_tab_search_results_company").html(data.html_table); // not working if I call it a second time } }); …

20.02.2025
My Django Project is sending the same email from different apps

I have a Django Project with two different apps: contact_us and booking. both are forms on different sections of the site. when the form for booking request is being sent it saves the info to the table and it is …

20.02.2025
Django Cloud Storage NoSuchKey

I deploy a Django/React project with GKE, Cloud SQL as DB, Cloud Storage for static file. When I trying upload files(both by Django admin and API), the url I get always tells me This XML file does not appear to …

20.02.2025
Cannot assign requested address: when sending e-mail from Django Docker container

I have this error message, when sending an e-mail from Django Docker container. OSError at /accounts/signup/ [Errno 99] Cannot assign requested address Request Method: POST Request URL: http://127.0.0.1:8000/accounts/signup/ Django Version: 4.0.10 Exception Type: OSError Exception Value: [Errno 99] Cannot assign …

20.02.2025
Webrtc shows extra stream with only one peer connection

I am trying to allow my webrtc video call meeting app have multiple peer connections and have the stream appear on the remote video call dynamically using javascript. I have only two tabs in two windows open on the video …

19.02.2025
Google OAuth 2.0: Login with Google works on localhost, but it doesn't work on hosting

I have a small Django website, and I've connected OAuth 2.0. It worked just fine on localhost. (In the Google Console, the authorized redirect URIs were: URI 1: http://127.0.0.1:8000/ URI 2: http://127.0.0.1:8000/google/login/callback/) Now I …

19.02.2025
Why is my email template in Django sending the whole model and not just the values input

I'm trying to email a copy of my contact form when the form is saved, but the template tags seem to be pulling the full model not just the inputs. I have no idea what I'm doing wrong here. My …

19.02.2025
Asyncio coroutine execution stopped and didn't return any error

I'm facing an odd behavior on one of my applications. So I have an application that has an POST entrypoint that receives a list of order id's and after processing each order it must inform an external API about the …

19.02.2025
User getting added to multiple permission groups instead of the one

In my application, when a user registers, they are identified as either a lecturer or a student. These are categorised as auth_groups, and users are assigned to one with these methods... def register_student(self, data): user = User.objects.create( user_id = …

19.02.2025
How to Restart a Django App via API After Modifying settings.py?

I am working on a Django project where I dynamically add new languages via an API. The workflow is as follows: Add a new language via the API (http://localhost:8000/core/swagger/). Via API /generate/ Generate the .mo and .po files after …

19.02.2025
Django - PostgreSQL docker - authentication issue [duplicate]

I've been trying to set up my first Django and PostgreSQL project with Docker containers. I followed this setup and everything went as expected: https://learndjango.com/tutorials/django-docker-and-postgresql-tutorial Opening my Django admin portal worked without any issues on: <a href="http://127.0.0.1:8000/admin/" …

19.02.2025
Heroku django Spatilite Unable to load the SpatiaLite library extension

Hi I get error while i'm trying to run my application on heroku with Spatialite: Unable to load the SpatiaLite library extension. Library names tried: mod_spatialite.so, mod_spatialite. my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # 'ENGINE':'django.contrib.gis.db.backends.postgis', # 'ENGINE': …

19.02.2025
Wagtail admin preview panel not working in production

The page preview in the Wagtail admin is working fine locally on my dev server, but in production, the preview is not displayed, just a spinning wheel. In the Chrome dev tools console, I see the error message: Uncaught SecurityError: …

19.02.2025
BooleanField form Checkboxes always empty in Django

I have a Model form that has some checkboxes. The database has values for these records for all rows. My form displays with empty checkboxes all the time. I can submit values via the checkbox and the database updates correctly, …

19.02.2025
Django Returning http instead of HTTPS in Prod

I deployed a Django app in an Ec2 with gunicorn and nginx but links generated by django are http instead of HTTPS. I have included the necessary settings. For example, when I have paginations, I got count&quot;: 12, &quot;next&quot;: &quot;http://my.example.com/article/?page=2&quot;, …

19.02.2025
Embedding a Web Application Using an Iframe

I have a Django application (A), and one of my clients wants to embed it within their application (B) using an iframe. The client application can be built with any framework, and we have no control over its code. Additionally, …

19.02.2025
Пагинация ListView редиректит на главную страницу

Делаю пагинацию на основе класса Listview. При нажатии на любую кнопку - &quot;Следующая страница&quot;, &quot;1 2 3&quot; меня редиректит на главную страницу &quot;home&quot;. Может кто ни будь сможет объяснить почему это происходит? Не прошу писать за меня код, просто объясните …

19.02.2025
How To Append & Send File data in a multipart react form with Django backend with Nested JSON

So, I have a form data with the corresponding JSON format project_status: 'OPEN', project_title: '', project_code: '', start_date: '', end_date: '', duration: '', engagement_year: '', financial_year: '', project_budget: '', domain: '', project_type: '', project_mou: null, other_docs: null, thirdAgencyDetails: { …

19.02.2025
Как подружить vscode с django и html

Пишу код с помощью vscode на django. В шаблоне есть тег В этот тег нужно добавить атрибут(свойство) enctype='multipart/form-data'. Так вот когда в пайчарм пытаешся добавить атрибут(свойство) он тебе подсказывает и название атрибута(свойства) и значение. Vscode вообще отказывается показывать подсказки по …

19.02.2025
Prevent Multiple Users from Booking the Same Table at the Same Time in Django

I have a Booking model where users can book a restaurant table for a specific date and time. However, I want to ensure that multiple users cannot book the same table at the same time. Here’s my model: class Booking(TimeStampWithCreatorModel, …

19.02.2025
Create a Mock Request for django rest framework

I am trying to createa mock Request for a post method in django rest framework and tried: factory = APIRequestFactory() data = {&quot;hello&quot;: 1} print(data) django_request = factory.post(url, data, format=&quot;json&quot;) print(&quot;body:&quot;, django_request.body) print(&quot;ct:&quot;, django_request.content_type) r = Request(django_request) print(r.data) The …

19.02.2025
Django css not rendering in Production

In my Django5 app everything works fine in development under venv but once I load the application into a Docker container with Debug=False I don't seem to get my CSS rendered properly. Whats really wierd is the CSS loading appears …

18.02.2025
How to disable the options in select with Django

I created a calendar with dates where appointments can be made. I then created a form to select appointments. I want each time an appointment is made, it to be grayed out for the exact day and time it was …

18.02.2025
Exception when trying to launch django project debug in VS code

Hi I have a django project (4.2.2) and when I start the project from the terminal inside VS Code using &quot;python3 manage.py runserver&quot; everything works perfectly. But I want to debug it so I created a launch.json file to start …

18.02.2025
Manually access content from Form fields in Django

I'm in a position where I would like to submit content to a form that is not defined in a Forms class. For example, in my forms.py: class AnalyseForm(forms.Form): TYPES = (('a', 'Type A'),('b', 'Type B'), ('c', 'Type C')) filename …

18.02.2025
Не могу создать суперюзера в джанго

При вводе пароля и при повторном вводе пароля пишет что это поле не может быть пустым и не создаётся ничего, хотя пароли я ввожу нормально и они уверен совпадают

18.02.2025
Не получается отобразить данные из QuerySet в шаблонах Django

Пытаюсь реализовать простой поиск данных на сайте. Если в шаблоне &quot;search_results.html&quot; указываем тег a, то вся информация, которая в нём находятся не отображается, в случае же если убрать тег a, то всё работает, почему так может происходить? То есть - …

18.02.2025
How to Implement Media File Upload Limits and Through Models in Django API for Large Real Estate File Management System?

I am building a large real estate file management system using Django API. I have created a separate app for media handling, and in my model, I want to enforce the following limits: A single featured image A gallery with …

18.02.2025
Прблемы со статикой и медиа. Пробовала всё

Base.html &lt;!DOCTYPE html&gt; &lt;html lang=&quot;ru&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; {% load static %} &lt;title&gt;{% block title %}Мой сайт рецептов{% endblock %}&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css&quot; integrity=&quot;sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z&quot; crossorigin=&quot;anonymous&quot;&gt; &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.googleapis.com&quot;&gt; &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.gstatic.com&quot; crossorigin&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;{% static …

18.02.2025
Why is my Django serializer returning only Match data and not including related Score data in the API response?

I'm working with Django REST Framework and trying to create an API endpoint that returns live match details along with their associated scores. I have two models, Match and Score, where Score has is associated with Match with a foreignkey. …