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

20.05.2025
Django django-admin-async-upload returns 302 redirect to 404 page in staging environment

I'm using the django-admin-async-upload library to handle asynchronous file uploads in my Django project. Everything works perfectly in my local development environment. However, when I deploy to the staging environment, attempting to upload a file results in a 302 redirect, …

20.05.2025
Using the Django REST Framework, how can I set a field to be excluded from one view, but included in an other, without much bloat code?

For example, if I had these models, how can I make sure that only the name of the house is displayed in one view, and all of it's properties are displayed in an other. Also, how can I display the …

20.05.2025
How to handle existing data when introducing an intermediate model between a base model and a child model in a Django Polymorphic inheritance hirarchy

Current models: class Task(PolymorphicModel): pass class DownloadTask(Task): pass New models: And now i want to do add a new layer called VirtualTask: class Task(PolymorphicModel): pass class VirtualTask(Task): pass class DownloadTask(VirtualTask): pass Migration it looks like this: class Migration(migrations.Migration): …

19.05.2025
Django Forms - How can I update a form with a disabled required field?

I have a Django Model with one required field (shpid). I want to set this field to disabled when updating the form. Although the value of this field is shown and disabled when the template is first displayed I get …

19.05.2025
Wagail wont show Preview mode for pages on live server

Preview works fine locally but not on server.. I get the following error in browser console Error invoking action "load->w-preview#replaceIframe" SecurityError: Failed to read a named property 'scroll' from 'Window': Blocked a frame with origin "https://chandankhatwani.pythonanywhere.com" from accessing a …

19.05.2025
Permission Denied while building Django project with Docker

I'm trying to build a Django project with Docker, but I always get this error and I don't know how to handle it: /usr/local/lib/python3.13/site-packages/django/coremanagement/commands makemigrations.py:160: RuntimeWarning: Got an error checking a consistent migration history performed for database connection …

19.05.2025
Server requirements to host Django + MySQL + Media Files

I have developed an django based fully dynamic web application. Now I am deploying it & facing issue with the compatibility of the droplets. How much vCPUs required? How much RAM required? How much Storage required? I have …

19.05.2025
Why does my Django website show 'Future home of something quite cool' after hosting on GoDaddy

"Whenever I host my website on GoDaddy.com and click on the homepage, it shows a message: 'Future home of something quite cool.'"

19.05.2025
Making Headless Website backend in Django, files are becoming lengthy and unreadable, is there any better and scalable approach? [closed]

I am working on a headless website project, where I am implementing the backend through django using django-rest-frameworks, till now I was using this structure my_project/ ├── manage.py ├── my_project/ │ ├── __init__.py │ ├── asgi.py │ ├─ settings.py │ …

19.05.2025
Form Tools Summary page redirection

I am not able to post all the code however I will try my best to explain and hopefully someone will be able to assist! I am using Django's formtools. I have four sections of a form, they are each …

19.05.2025
What are the downsides of default ordering by PK in Django?

Django models now support default ordering, via Meta.ordering. What are the downsides to putting ordering = [&quot;pk&quot;] on my base model? In particular, I'm curious about the performance impact. The Django docs have a <a href="https://docs.djangoproject.com/en/5.2/topics/db/optimization/#don-t-order-results-if-you-don-t-care" rel="nofollow …

18.05.2025
Why my EC2 instance is not recognizing my app?

Im new in AWS and i tried migrating my files in EC2 and i see this error, is it a problem in my structure? I would really appreciate any help since im working in my portfolio and i cant seem …

18.05.2025
Django DRF, Cannot reproduce POST request using APIClient and APITestCase, payload fields are removed

I have the following setup in Django DRF: class TagSerializer(serializers.Serializer): id = serializers.UUIDField(read_only=True) name = serializers.CharField(required=True) style = serializers.JSONField(read_only=True) class TagCreationMixin: def create(self, validated_data): tags = validated_data.pop(&quot;tags&quot;, []) failure_mode = self.Meta.model.objects.create(**validated_data) for tag in tags: current_tag, _ = models.Tag.objects.get_or_create(**tag) failure_mode.tags.add(current_tag) …

17.05.2025
VS Code python extension seeing some not all Django class

Simple problem: the Python extension of VS Code is not seeing a Django class, while all other classes in same file are presented. Restarting, disabling/enabling, switch to pre-release for the extension doesn't change anything. Confirmed it was the extension as …

17.05.2025
Django DRF, create an Item with associated tags whether they exist or not

I have the following create function for ItemSerializer class. It aims to create new Item with tags, creating tags on the fly if they does not exist or getting them if they exist. class TagSerializer(serializers.ModelSerializer): class Meta: model = models.Tag …

16.05.2025
Django manage command set stdout and stderr

Is there a way to set stdout and stderr from base_stealth_options in BaseCommand when running the django command? I can't find any documentation about how to use those options. For example, I would like to set stdout and stderr to …

16.05.2025
Where to set up subdomain routing? Front-end (React) or Django (Backend)?

I'm currently building a multi-tenant web application using Django and React. Right now, each user's page is available at a URL like https://mywebsite.com/. However, I want to change this so that each user has their own subdomain, …

16.05.2025
My VM not connecting to MySQL – 2002 error

I’m currently experiencing issues with my virtual machine named &quot;monitoramentoati&quot;. When trying to access my application through the domain https://monitoramentoati.camf.org.br/admin/login/, I encounter the following error from Django: &quot;OperationalError at /admin/login/ (2002, &quot;Can't connect to local MySQL server …

16.05.2025
Creating TabularInline in Django Admin View for inherited Many2Many relation

I have a Tag Model and Mixin that is used for adding tags to entities whenever it is needed. class Tag(models.Model): name = models.CharField(max_length=64, unique=True) class TagMixin(models.Model): class Meta: abstract = True tags = models.ManyToManyField(Tag, blank=True) To create new …

16.05.2025
Airwallex Payment Link not redirecting to custom redirect_url after successful payment

I'm integrating Airwallex payment links into my web application. After a successful payment, instead of being redirected to my custom success URL (e.g., https://example.com/paymentsuccess), users are taken to the Airwallex default success page. Here's …

16.05.2025
What is the best and production-safe way to handle long process them efficiently in Django, ideally with parallel processing?

I'm working on a Django app where users upload large .txt files that need to be parsed and stored in a PostgreSQL database. The files can contain hundreds of thousands of lines, and processing them can take a long time. …

15.05.2025
Getting this error had repository from git and python virtual environment is activated just getting problem to activate from source env/bin/activate

WARNINGS: ?: (staticfiles.W004) The directory 'C:\Ansh\ecom\django_project_boilerplate\static_files' in the STATICFILES_DIRS setting does not exist. System check identified 1 issue (0 silenced). You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): auth. Run …

15.05.2025
Django view doesn't save form changes

Django 5.2, python 3.12.5 . I'm using in-built user model and no errors appear when I press the submit button. I created a view based on UpdateView and use the built-in UserChangeForm. The form actually returns 200 response code. I …

15.05.2025
Post data into database failed with form invalid message

#I can not send data to my db, please help me to check.# Here is the model Model: class f_groupe_user(models.Model): IDF_GROUPE_USER=models.AutoField(primary_key=True) LibELE_GROUPE= models.CharField(max_length=120) Soc_sigle = models.CharField(max_length=120) created_at=models.DateTimeField(auto_now_add=True) updated_at= models.DateTimeField(auto_now=True) UTIL_CREATION= models.CharField(max_length=120) UTIL_MODIF= models.CharField(max_length=120) def __str__(self): return self.LibELE_GROUPE Here is …

15.05.2025
Изменить значение "не найдено". это неверная ошибка в представлении или имени функции

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

15.05.2025
Ошибка обрезки изображений django: объект 'ImageField' не имеет атрибута 'image_field'

Я использую Amazon S3 в качестве хранилища файлов. Я попробовал использовать django image chopping 1.7 для обработки фотографий, это работает для отображения изображения без обрезки изображений django на веб-сайте, и я прочитал официальную документацию cover_photo = models.ImageField(upload_to='package_inner_photos', null=True, blank=True) cover_photo_cropping …

15.05.2025
Формы Django Crispy с помощью Tailwind CSS 4.0: в форме появляется нежелательное направленное вниз курсор

Я использую: Django 5.2.1 Попутный ветер CSS 4.0 хрустящий попутный ветер 1.0.3 джанго-хрустящие формы 2.4 Я использую пакет шаблонов Tailwind, который определен в моем settings.py. Когда я отрисовываю свою форму в моем шаблоне 'concert_form.html', используя crispy-forms, после одного …

14.05.2025
Ошибка Stripe InvalidRequestError в /subscription/ Request req_F6PVTyTtfDXnIf: вы передали пустую строку для 'line_items[0][price]'. Мы принимаем пустые значения

Я пытаюсь настроить услугу подписки на своем веб-сайте с помощью Django. models.py from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now class Subscription(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) customer_id= models.CharField(max_length=255) subscription_id = models.CharField(max_length=225, unique=True) product_name = models.CharField(max_length=255) …

14.05.2025
Как отправить видео (mp4) в качестве ответа

Мне нужно знать, как я могу отправить видеофайл в качестве ответа в django. React+Django это мой код на django, который обрабатывает запрос. u/csrf_exempt def get_video(request): view_logger.info("Fetching video") try: if not LOGS_FOLDER_PATH: view_logger.warning("LOGS FOLDER PATH not present") return HttpResponseNotFound("Logs folder path …

14.05.2025
Django ModelForm не выполняет предварительное заполнение полей при обновлении экземпляра – ошибки "Это поле является обязательным"

Я создаю проект на Django-Unittest. Идея в том, чтобы позволить преподавателям нашего университета создавать и проводить онлайн-тесты на нем. Проблема, с которой я столкнулся, связана со страницей update_test.html, которая не выполняет предварительную обработку данных. Вот функция просмотра. @login_required …

14.05.2025
Можно ли использовать DRF's datetimepicker и включить смещение UTC для временных меток в ответный JSON?

Я пытаюсь использовать веб-интерфейс API для просмотра в Django Rest Framework. У меня есть объекты с данными временных меток в таком формате: "2025-05-08T22:02:58.869000-07:00". Но требуемый формат для datetimepicker в Django не поддерживает смещение UTC или последние три значащие цифры в …

13.05.2025
Как я могу установить для javascript const значение в элементе формы, которое может быть либо выпадающим списком, либо переключателем с флажком?

У меня есть html-форма на сайте django, которая используется как для добавления, так и для обновления. Если форма предназначена для новой записи, я хочу, чтобы поле estimateType было переключателями с тремя вариантами выбора, одним из которых по умолчанию является checked. …

13.05.2025
Django фильтрует объекты, которые содержат значение поля JSON, в списке значений JSONField другой модели с тем же "ключом".

Я не уверен, что название этого поста помогло вам понять суть проблемы, но позвольте мне объяснить: У меня есть модели: class ItemCategory(models.Model): name = CharField() class Item(models.Model): brand = CharField() model = CharField() category = ForeignKey(ItemCategory) attributes = JSONField(default=dict) # …

13.05.2025
Как создать форму Django (имена и элементы) из столбца фрейма данных или столбца набора запросов.?

Как я могу создать форму, даже если это не форма Django, а обычная форма с помощью ввода? Чтобы имена и элементы полей формы были взяты из столбца фрейма данных или столбца набора запросов. Я бы хотел, чтобы поля формы не …

13.05.2025
Приложение Django: поле модели или приложение для условий

В настоящее время я планирую создать Django-приложение, которое регулярно запускало бы задания в соответствии с условиями. Регулярно приложение должно проверять, выполняются ли условия в каком-либо из заданий, и запускать их с положительным результатом. Подумайте о условиях …

13.05.2025
Django PWA нельзя установить на Android

Я разработал простой проект django PWA (без опубликованного приложения django-pwa) для тестирования автономных функций. Я развернул свой проект на pythonanywhere: lecarrou.pythonanywhere.com. Когда я устанавливаю свое приложение на рабочий стол, оно становится доступным для установки (Chrome и Edge). Но у меня …

13.05.2025
Подключение к локальному api Flutter не будет работать на эмуляторе / Android sid

Я создал конечную точку в своем приложении Django, например: /accounts/api/login/. Она проверяет входные данные и возвращает JSON. Что касается кода Visual Studio, команда flutter run позволяет мне успешно войти в систему. Но если я попробую запустить приложение на эмуляторе Android …

13.05.2025
Django runserver завершает работу с ошибкой "AttributeError: класс должен определить атрибут 'type'" при использовании Python 3.13

Python manage.py runserver Но я получаю следующую обратную связь: Traceback (most recent call last): File "C:\Users\...\manage.py", line 22, in &lt;module&gt; main() ... File "...django\core\files\locks.py", line 32, in &lt;module&gt; from ctypes import ( File "...\Python313\Lib\ctypes\__init__.py", line 157, in &lt;module&gt; …

13.05.2025
Ошибка FieldError в /chat/search/ Неподдерживаемый поиск 'groupchat_name' для CharField или join в поле, которое не разрешено

Я пытаюсь найти группы в чате по названию комнаты чата. Я использую Q-запрос Django... models.py class ChatGroup(models.Model): group_name = models.CharField(max_length=128, unique=True, default=shortuuid.uuid) groupchat_name = models.CharField(max_length=128, null=True, blank=True) picture = models.ImageField(upload_to='uploads/profile_pictures', default='uploads/profile_pictures/default.png', blank=True) about = models.TextField(max_length=500, blank=True, null=True) admin = …

13.05.2025
Использование библиотеки django-okta-auth: проблема с циклическим входом в систему при запуске в LocalHost

Я использую платформу Okta и Django для разработки веб-приложения, и я столкнулся с ситуацией на моем локальном хостинге, которую, похоже, я не могу обойти. Я вхожу в виджет входа в Okta, он приводит меня к проверке Okta, а затем перенаправляет …