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

09.06.2025
How do I prevent a user from creating multiple objects within 24 hours in Django

I'm trying to prevent users from creating more than one Mining object within a 24-hour period in my Django project. I chose to use Django signals, specifically the pre_save signal, to enforce this rule globally—regardless of whether the object is …

09.06.2025
Trying to send basic string to Django Backend via POST request using axios but no data is sent

I've been trying a basic string to Django backend from frontend using axios.post call. Connection is ensured and backend side detects the request but the data is empty. Frontend side: const axios = Axios.create({ baseURL: API_URL, headers: { 'Content-Type': 'application/json', …

09.06.2025
How to get Custom Adapter to respect the 'next' URL query parameter

I am using allauth in my Django project and I have set up a custom account adapter which I have specified in settings.py - ACCOUNT_ADAPTER. My issue is once the user logs in in at a URL like /accounts/login/?next=/checkout/, my …

08.06.2025
Не работают ссылки на сайте в Django

Не работают ссылки, хотя вроде всё прописано верно. В файле urls.py: from django.urls import path from . import views urlpatterns = [ path ('', views.reg, name = 'Reg_page'), path ('about/', views.about, name = 'About') ] В файле views.py: def …

08.06.2025
Django Field errors not displaying

Here is my forms.py code: from .models import User class userRegistrationForm(forms.ModelForm): password = forms.CharField(widget = forms.PasswordInput()) confirm_password = forms.CharField(widget = forms.PasswordInput()) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email','password'] ``` Here is my views.py code: …

08.06.2025
Фоновые задания в Джанго

Никак не могу понять - с какой стороны подойти к такой задаче: В базу надо записывать данные с определенной периодичностью. Как в Джанго реализованы фоновые задачи, выполняемые по расписанию? В идеале было бы хорошо создать внутри скрипт и заполнять данными …

08.06.2025
Django - Testing async management command not working as expected

To give some context, i made a async function which works fine when testing manually but when I use Django's testcases, the query is not returning anything back inside the async block, if I try the same query outside, it …

07.06.2025
Add functionality to model creation in django admin site

I creating a website using django. I want to add extra functionality to model creation and changing pages in standard admin site, that is input text field and button. Idea is to paste a link to post on another website …

07.06.2025
How to efficiently combine Redis-based recommendation scoring with Django QuerySet for paginated feeds?

I'm building a marketplace app (think classified ads with negotiations) and trying to implement a personalized recommendation feed. I have a hybrid architecture question about the best way to handle this: Current Setup: Django backend with PostgreSQL for product …

07.06.2025
'User' object has no attribute 'profile' django profile update problem

I am new to django and currently learning and i have encountered a problem that i just cant seem to solve. from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm from django.contrib.auth.decorators import login_required …

07.06.2025
How to integrate a PyTorch YOLO ensemble model (.pt file) into a Django web app for real-time image predictions?

I'm building a Django web app where users can upload images to detect objects using a YOLO ensemble model saved as a .pt file. This model includes keys like 'model', 'names', 'stride', and 'ensemble_info'. So far, I can load the …

07.06.2025
How to make a one-off charge (no UI) reusing the saved customer after initial Checkout?

I’m implementing payments with Stripe and I’ve run into a flow I don’t know how to solve. I’d like to know the right or recommended way. Scenario First payment with UI: The user goes to my frontend, I use …

06.06.2025
Wagtail - How can I use a custom StructBlock with programmatically assignable default values?

I have created a StreamField for some of the site's settings. This StreamField contains a collection of a custom StructBlock, named FacetBlock. FacetBlock contains a BooleanBlock, a CharBlock, an IntegerBlock and a ChoiceBlock. Now I need to make the CharBlock …

06.06.2025
Performance issues when using Django's Min('id') in big table

I have a model Table which gets a new entry every few seconds, so it's a quite big table. class Table(models.Model): id: int pk: int timestamp = models.PositiveBigIntegerField(db_index=True) Now what i am trying to do is get …

06.06.2025
CS50W Project network, can't figure how to implement the Paginator

I've been trying to implement the paginator function for about two months now. I've tried many different approaches, but they always lead to new bugs. In views.py, I load the posts and send them to JavaScript. In loadPosts and loadProfile, …

05.06.2025
Django Celery: 6-second delay to register task from UI in Kubernetes environment – resource allocation?

We are seeing a ~6-second delay when a Celery task is triggered via the Django UI (e.g., my_task.delay()). Our stack runs on Kubernetes, and I'm wondering if this lag is due to resource constraints or something else. Key Services and …

04.06.2025
Getting "MySQL server has gone away" error on cPanel-hosted Django site

I'm hosting a Django project on a shared server using cPanel, and I’ve been running into a frustrating issue lately. On several pages across the site, I get a 500 Internal Server Error. After checking Sentry, I consistently see this …

04.06.2025
Can the Django development server be restarted with a signal?

I would like to be able to restart the manage.py runserver Django command using a signal (like in kill -HUP PID). Does Django even support this? SIGHUP, SIGINT, SIGTERM just exit the process. Tried pkill -HUP, didn't work.

04.06.2025
Running Django tests in parallel on MariaDB, get "No such file or directory: 'mysqldump'"

I have a Django project running locally, with its database as MariaDB 10.6 running in a Docker container. The Django tests work fine, but when I try to run them with a --parallel flag I get an error "FileNotFoundError: [Errno …

04.06.2025
Using custom trigram similarities with Django, Postgres and PgBouncer

I want to adjust pg_trgm.similarity_threshold on some of my queries. But since I'm using PgBouncer (in transaction pooling mode) to mediate access to my Postgres database, I want to be sure that when I'm done, the session value is set …

03.06.2025
Django POST error: response variable not associated with a value error

This one for python wizards. I got next code in some of my messenger class: response: Dict[str, Any] | None = None try: response = self.client.post("url/", data=payload) if not response or not response.get("ok"): logger.warning( "[MessageService sync_chat] " …

03.06.2025
Django ORM generating insane subqueries with prefetch_related - 3 second page loads

I'm losing my mind here. Been working on this e-commerce site for months and suddenly the product catalog page takes 3+ seconds to load. The Django ORM is generating absolutely bonkers SQL with nested subqueries everywhere instead of simple JOINs. …

03.06.2025
Python Django Error during rendering "template"

This is what im building I am currently developing a receipt system and when i run the application, i get this error, i have checked the settings.py and my app has been added to the list of installed apps, my …

03.06.2025
Best SMS Service Provider for Global OTP Verification and Phone Number Validation (Any Free Options?)

I'm implementing OTP verification for user signup/login in my application and I need a reliable SMS service provider. My main goals are: Global Reach – The service should support sending SMS OTPs to users in multiple countries. OTP Verification – …

03.06.2025
Is anyone faced this issue : SSL CERTIFICATE_VERIFY_FAILED certificate verify failed: Hostname mismatch, certificate is not valid for 'smtp.gmail.com'

When deploying an Django full stack app on GoDaddy VPS I came across this error, I have also changed server the the error still persists, my application use Celery for email tasks queues with Redis, I do not know what …

03.06.2025
Python Django Admin Form: show inline without rendering a form

I have a Django admin page which allows me to edit a model in my domain. The ModelAdmin looks like this: @admin.register(models.VehicleTemplate) class VehicleTemplateAdmin(ModelAdminBase): list_reverse_relation_inline = False search_fields = ["name", "description"] list_display = ["name", "description", "parent", "status"] inlines = [VehicleInline] …

03.06.2025
Django-allauth - Make phone number optional for SocialLogin

I am using django-allauth in my project and I have configured Google as a SocialAuth provider. I have a custom signal receiver that updates the phone number on the SocialAuthAccount after the user signs up. But currently the system throws …

02.06.2025
Decouple.UndefinedValueError: SECRET_KEY not found when using python-decouple in Django

I'm getting the following error when I try to run my Django project: decouple.UndefinedValueError: SECRET_KEY not found. I'm using python-decouple to manage environment variables. In my settings.py, I have: from decouple import config SECRET_KEY = …

02.06.2025
Сканирование файлов на вирусы в S3

Всем привет! Разрабатываю сайт на Django/React с хранением файлов в S3 хранилище от Selectel, весь проект разворачиваю в Docker. У меня возник вопрос касаемо того как проверять загружаемые файлы в S3 на безопасность. Вижу три основных пути реализации механизма, но …

02.06.2025
Django: Migrations generated again after deployment, even though no model changes were made

As part of our project, we made some changes, merged the PRs, and deployed the latest code to our development server. However, after deploying, we noticed that Django is generating new migrations, even though there were no changes made to …

02.06.2025
Is there an app available to Test emails locally using a local SMTP server on Linux and Windows [closed]

I want to test emails from django app, i was using mailtrap before but now i want to test my emails locally. For Django developers, transitioning from a remote email testing service like Mailtrap to a local solution is often …

02.06.2025
Combine multiple `shell` commands across apps using `get_auto_imports`?

Django 5.2 introduced the ability to customize the shell management command by overriding the get_auto_imports() method in a management command subclass (see the release note or this page of the doc). That's a nice …

02.06.2025
Issue with browser-tools@2.0.0 from circleci

I am trying to run Selenium tests for a Django app on CircleCI. The browser tools are updated 28.05.2025, but I still can't manage to configure it... In my config.yml I have version: 2.1 orbs: python: circleci/python@3.1.0 slack: circleci/slack@4.10.1 browser-tools: …

02.06.2025
Django test fails on github-actions, works locally

I am ahving a problem. I am following a tutorial and wrote a wait for db command in my django project to wait until db is available and then run my tests. The command is below: docker compose run --rm …

01.06.2025
Django админка - изменить отображаемые данные

Модель: class Access(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=300, blank=True) В админке Django в таблице Access столбец user - отображает username пользователя. Вопрос в том, можно ли изменить значения в этом …

01.06.2025
Django problem, when I pass product id by get method

In href tag I want to send product id but this code showing an error. Could not parse the remainder: 'data.id' from ''viewproduct'data.id' {% for data in data %} <div class="item mt-5"> <div class="card" > **<a href={% url 'viewproduct'data.id …

31.05.2025
What Python topics should I learn first as a beginner, and where can I find free resources to practice them?

I'm a computer science student currently learning web development and just getting started with Python. I've covered some basics like variables, data types, and simple loops, but I'm not sure what to focus on next or how to build a …

31.05.2025
Multiple permissions for multiple roles in django

Im currently working on a news project which i have news-writer , article-writer etc . im using proxy models , i created a base User model and i created more user models in the name of NewsWritetUser and it has …

31.05.2025
Django + Celery + PySpark inside Docker raises SystemExit: 1 and NoSuchFileException when creating SparkSession

I'm running a Django application that uses Celery tasks and PySpark inside a Docker container. One of my Celery tasks calls a function that initializes a SparkSession using getOrCreate(). However, when this happens, the worker exits unexpectedly with a SystemExit: …

31.05.2025
Django overwriting save_related & copying from linked sql tables

In django python, I am able to overwrite the save_related function (when save_as = True) so the instance I am trying to copy is saved and copied properly. When I save, though, I want other objects in other tables linked …