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

27.08.2025
Error: "get" is not a known attribute of "None" (reportOptionalMemberAccess)

I use PyRight to check my Django code. It complains about that class FooForm(ModelForm): def clean(self): cleaned_data = super().clean() start = cleaned_data.get("start_date") # <------- here error: "get" is not a known attribute of "None" (reportOptionalMemberAccess) …

26.08.2025
Django 1.5.1: diagnose and fix Report

I've been handed a rather old Django installation to support, with the specific request to re-enable a report that used to go out every week or so, but stopped showing up a few months ago. Django v 1.5.1 Python 2.7.3 …

26.08.2025
How to handle feature and permission-based authorization in Next.js without delaying initial render?

I’m building a multi-tenant SaaS application with Django Ninja as the backend and Next.js as the frontend. I’m running into a problem around handling RBAC permissions and org-level feature entitlements without causing bad UI behaviour. Current setup The app …

26.08.2025
Как мне отобразить определенную информацию в html странице django из базы sqlite3?

Создаю тестовый проект в Django rest api. Есть данные из sqlite3: [ { "id": 1, "title": "test", "content": "test", "idcard": "Card", "idmenu": "Info", "author": "Admin", "date": "3" }, { "id": 2, "title": "Name table1", "content": "table1 will be here", "idcard": …

25.08.2025
Patterns for testing web API permissions

I am working on a cookie cutter JSON web API. Think /items/<id> with your typical CRUD of delete, patch, get, and post. Recently, we started rolling out a new permissions model for the API, where certain operations are forbidden based …

25.08.2025
Django 'join' tabels

I have 3 Tabels in Django class Transactions(models.Model): public_key = models.ForeignKey(Keys, on_delete=models.CASCADE) txid = models.CharField(max_length=30) timestamp = models.DateTimeField() hash = models.CharField(max_length=64) block = models.IntegerField() amount = models.IntegerField() saldo = models.IntegerField() fee = models.IntegerField() fiat_CHF = models.FloatField(default=0) fiat_USD = models.FloatField(default=0) fiat_EUR …

25.08.2025
Django join where values not null

I have 3 Tabels in Django class Transactions(models.Model): public_key = models.ForeignKey(Keys, on_delete=models.CASCADE) txid = models.CharField(max_length=30) timestamp = models.DateTimeField() hash = models.CharField(max_length=64) block = models.IntegerField() amount = models.IntegerField() saldo = models.IntegerField() fee = models.IntegerField() fiat_CHF = models.FloatField(default=0) fiat_USD = models.FloatField(default=0) fiat_EUR …

25.08.2025
So many terminal messages when starting django runserver

When I start python manage.py runserver I get many messages similar to the following: File C:\Users\PC\OneDrive\Documents\DoseSaaS\DoseV3MasterSaaS\templates\admin\dose\tenant\change_list.html first seen with mtime 1754471094.0 to the point it fills the terminal window. How do I stop this? Could not find anything …

24.08.2025
Django REST Auth password reset email sends API URL instead of frontend React URL

I am using dj-rest-auth with Django as the backend and React.js as the frontend. I want the password reset email to point to my React frontend URL, not the default API endpoint. Sending: http://localhost:8000/api/auth/password/reset/confirm/{uidb64}/{token} Correct url: https://my-domain.com/password-reset/confirm/{uidb64}/{token} .env <pre class="lang-json …

23.08.2025
Show the text from a Json file in Django template

I am starting learn django,I have made some basic templates/views and want to show the text from a json file located in the assets/jsons folder.The file is called &quot;quotes.json&quot; The content of the json file: { &quot;emp_details&quot;: [ { &quot;emp_name&quot;: …

23.08.2025
Django cannot register oauth2_provider and rest_framework to INSTALLED_APPS

I am working on this weekend project, to learn Django and I am stuck. Before adding the REST framework (one to last commit in the repo), everything was working just alright. Once I added …

22.08.2025
Managing Django groups and permissions for custom users

For my Django projects, I am used to creating a custom user model and managing what my user can do for a specific route using a roles field like this: class User(AbstractBaseUser, PermissionsMixin): name = models.CharField(&quot;full name&quot;, max_length=255, blank=True) email …

21.08.2025
Stripe webhooks not firing in Django app during normal checkout flow

I'm integrating Stripe with my Django app (using Django REST Framework). I've set it up to accept POSTs, and when I use the Stripe CLI to trigger events, everything works perfectly. Example Stripe CLI command: stripe listen --forward-to localhost:8000/webhooks/api/v1/stripe-webhook/ …

20.08.2025
Django connection_created signal is causing problems when testing

In my django application I have a list of notification types and I want to allow customers to subscribe to one or more notification types. Each notification type has somewhat of a custom logic so the code of each notification …

20.08.2025
535, b'5.7.139 Authentication unsuccessful, basic authentication is disabled

I have a website that uses an email contact form. Recently been told it does not work. When I recreated the error in development I got the error 535, b'5.7.139 Authentication unsuccessful, basic authentication is disabled. I read online that …

19.08.2025
Stripe: "No signatures found matching the expected signature for payload" using Django Rest Framework and request.body

I'm integrating Stripe webhooks into my API, which is built with Django Rest Framework (DRF). Here’s my webhook view: class StripeWebhookView(APIView): permission_classes = [AllowAny] # Public webhook def post(self, request, *args, **kwargs): payload = request.body sig_header = request.headers.get('stripe-signature') …

19.08.2025
Using list which depends on another list in excel using python

I have a requirement to create dependent dropdowns in excel using python. import os import openpyxl from openpyxl.styles import Border, Side, PatternFill, Font, Alignment, numbers from openpyxl.worksheet.datavalidation import DataValidation from openpyxl.workbook.defined_name import DefinedName def create_dynamic_excel_bytes(sheets_config, file_name): wb = openpyxl.Workbook() ws_hidden …

19.08.2025
JsonField in Django Admin as Inline

I have a JsonField in my Model, its structure is a dict. class MyModel: final_result = models.JSONField() But it's pretty big, and it's hard to edit it with any JSON widget. So I thought, that maybe I need to …

18.08.2025
Trying to do Selenium testing in Django in Docker getting ERR_CONNECTION_REFUSED

I am trying to get Selenium testing going in Docker with Django. But I keep getting ERR_CONNECTION_REFUSED when using the live_server_url. I have tried to use django's container with f&quot;http://django:{self.port}{reverse('account_login')}&quot; I have also tried to use the ip address of …

17.08.2025
Как пересоздать миграции с нуля в БД в Django?

Такая проблема: я экспериментировал с ORM и создавал/модифицировал модели. В итоге &quot;захламил&quot; всю базу данных (соответственно, начались ошибки при применении новых миграций). Есть ли какой-то способ с помощью средств самого Django очистить БД и заново провести с нуля все миграции? …

16.08.2025
'RegisterSerializer' object has no attribute '_has_phone_field'

Dj-rest-auth library has been returning this error when I send a request into the /registration endpoint from rest_framework import serializers from dj_rest_auth.registration.serializers import RegisterSerializer class RegSerializer(RegisterSerializer): phone = serializers.CharField(required = False) def get_cleaned_data(self): data= super().get_cleaned_data() data['phone']=self.validated_data.get(&quot;phone&quot;,&quot;&quot;) return data …

16.08.2025
Организация тестирования проектов Django

Официальная документация не дает ответ на этот вопрос. Там общие положения как писать и как запускать. Что имеем Проект на django 9 приложений мультиязычность дополнительно web api тестовая среда с написанными тестами (application1/tests/, application2/tests/ etc.) Вопрос Как отделить …

15.08.2025
Django REST API endpoints URL paths

I have a Django 4.2 app with Postgres DB and REST API. My urls.py contains this path in urlpatterns: path('create/&lt;int:pk&gt;/&lt;str:name&gt;/', ComponentCreate.as_view(), name='create-component') ComponentCreate in views.py relates to a simple DB table (component) with id as integer primary key and name …

15.08.2025
Deploy a dockerized monorepo to Railway

I'm trying to deploy my dockerized monorepo (Django &amp; Next.js) project to Railway but I keep failing. My folder structure railway.tom [build] builder = &quot;dockerfile&quot; # Frontend service [services.frontend] builder = …

15.08.2025
DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread

I'm having the following issue, when I try to execute my Django tests: /Users/myUser/Desktop/myProject-py/src/project/project/billing_v2/tests/test_accounting_integration_heading.py::AccountingIntegrationHeadingAPITests::test_create_accounting_integration_heading failed with error: Test failed with exception request = &lt;SubRequest '_django_setup_unittest' for &lt;TestCaseFunction test_makemigrations_command&gt;&gt; django_db_blocker = &lt;pytest_django.plugin._DatabaseBlocker object at 0x10602ae80&gt; @pytest.fixture(autouse=True, scope=&quot;class&quot;) def _django_setup_unittest( request, django_db_blocker: …

14.08.2025
How to execute a multi-statement Snowflake SQL script (DECLARE, DDL, DML, CASE) from Python with parameters and fetch SELECT results?

I’m new to Python and Snowflake’s scripting blocks. I want to keep a multi-statement Snowflake SQL script in a .sql file and execute it from Python with parameters. The script may include DECLARE, DDL, DML, CASE logic — basically SP-like …

14.08.2025
InlineKeyboardButton with callback_data doesn't work

InlineKeyboardButton with callback_data doesn't work. When I click on it, nothing happens. Here is how I create the button: from django.apps import apps from asgiref.sync import sync_to_async from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton, WebAppInfo from telegram.ext import CommandHandler, ApplicationBuilder, MessageHandler, …

13.08.2025
Как в Django вывести в HTML отдельно "родителя" и "наследников"?

Требуется в таблицу HTML отдельно вывести &quot;родителя&quot; (тип прибора) и &quot;наследников&quot; (модификация прибора). Пока получется выводить все в один столбец - т.е. если у прибора указан &quot;Тип&quot;, то выводится его тип, а если указана модификация, то выводится модификация (см. скриншот), …

13.08.2025
Snyk flags code as path traversal vulnerability but the code seems ok

In my django python application I have such functions: def get_sanitized_file_path(file_path: str) -&gt; Path: ALLOWED_BASE_DIR = Path(settings.MEDIA_ROOT).resolve() if not file_path: raise SuspiciousOperation(&quot;No file path provided&quot;) try: file_path = os.path.normpath(file_path) if &quot;..&quot; in file_path: raise SuspiciousOperation(&quot;Path traversal attempt detected&quot;) # Security: …

13.08.2025
How to handle customer.subscription.created if a organization(tenant) doesn’t exist yet in Stripe webhook?

I'm using Django and Stripe for a multi-tenant SaaS. I register users and organizations manually from a view, and I create the customer and subscription using Stripe API before saving to the database. class TestRegisterView(APIView): permission_classes = () …

13.08.2025
Testing a complex multipart custom django form

I have 2 complex custom form classes; each class contain several subforms (model form, formset and sometimes nested formset). I have written tests for both of them : tests of the form methods (init, full_clean, is_valid) using post data. I …

11.08.2025
Items Not Getting Added To Anonymous Users Cart?

I wanna make non logged in users can added items to thier cart but when i click add to cart no item getting added to thier cart this is my views.py : from django.shortcuts import render from django.http import JsonResponse …

11.08.2025
Implementation of MultiPolygonZMField in GeoDjango/django

I have an .shp file and the ogrinfo resulted as follow # ogrinfo -so AnalysisV1.shp AnalysisV1 INFO: Open of `AnalysisV1.shp' using driver `ESRI Shapefile' successful. Layer name: AnalysisV1 Metadata: DBF_DATE_LAST_UPDATE=2025-06-23 Geometry: 3D Measured Polygon Feature Count: 223252 Extent: …

11.08.2025
Why does my Django models.Manager return all objects on a relationship?

I don't particularly understand what's going on here, but it seems that super().get_queryset() doesn't do what I think it does? I have 1:N relationship, and the default FK reverse lookup works: &gt;&gt;&gt; for thing in this.thing_set.all(): ... print(thing.this) Each …

09.08.2025
How do i make the names appear more to the left and reduce the spacing between the checkbox and the name?

I’m rendering a Django form field (CheckboxSelectMultiple) inside a custom dropdown. The checkboxes and labels (names) are visually shifted to the right. I want the dropdown to look like a clean checklist, with all checkbox icons aligned in the same …

09.08.2025
Stripe Subscription: latest_invoice.payment_intent raises AttributeError: payment_intent

I'm trying to create a subscription in Stripe using Python and the official library, with the goal of obtaining the client_secret from the initial invoice's PaymentIntent to complete payment on the frontend. Here is the code I'm using: <pre class="lang-py …

08.08.2025
Error d"MIME (« text/html ») incorrect (X-Content-Type-Options: nosniff)" on deploy Django project with gunicorn and Apache

I'm trying to deploy a Django project with Gunicorn and Apache. The gunicorn is configured and working --&gt; no problem on this side The problem is with the statics files, i configure an apache conf : &lt;VirtualHost *:80&gt; ProxyPass /static/ …

07.08.2025
How to re-compile static/css/site-tailwind.js file in Django project

I'm developping a Django project inside a docker container, but am running into a problem. I cannot get the docker container to recompile the static/css/site-tailwind.css file. I'm trying to include components which are declared in a assets/styles/site-tailwind.css file, but however …

07.08.2025
Ошибка ModuleNotFoundError: No module named 'distutils' при создании проекта Django

Делал по инструкции.(Django 2.2) Сначала создал виртуальную среду. Затем установил Django: (projectlol) C:\Users\stefi&gt;pip install django==2.2 Collecting django==2.2 Downloading Django-2.2-py3-none-any.whl.metadata (3.5 kB) Collecting pytz (from django==2.2) Using cached pytz-2025.2-py2.py3-none-any.whl.metadata (22 kB) Collecting sqlparse (from django==2.2) Using cached sqlparse-0.5.3-py3-none-any.whl.metadata (3.9 kB) Downloading …

07.08.2025
Unable to create POST request via HTMX for WebSocket

When trying to send a form in real-time chat, a GET request (HTTP GET /?csrfmiddlewaretoken=some_csrf) appears in the console instead of POST, and the program does not reach the consumer. Django-v5.2.4, daphne-v4.2.1 chat.html {% extends 'layouts/blank.html' %} {% block …