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

25.04.2024
I want to link my subcategory to related category in forms.py. How to do that?

I'm currently working on a Python project where I'm trying to get category from its own related subcategories. However, I'm encountering an issue where the subcategory field, it doesn't show anything. There are 4 files that i'm uploading: This …

25.04.2024
Django does not access PostgreSQL Database using Docker

Here is the error message: Got an error checking a consistent migration history performed for database connection 'default': connection failed: could not receive data from server: No route to host Here is my .env POSTGRES_DB=ibm_skiller POSTGRES_PASSWORD=mYP@sSw0rd POSTGRES_USER=ibm_skiller POSTGRES_HOST=172.19.0.2 POSTGRES_PORT=5432 …

25.04.2024
Serialize a nested object with Django Rest Framework

I'm currently trying to serialize the following object into the models listed below, the current relationship is A Category has many quizzes, a quiz belongs to one category, while containing many questions, a question belongs to a quiz, while containing …

25.04.2024
I couldnt redirecting my django app from int to string in the url

I'm having trouble with my Django URL patterns. The URL exercise4/1/ is not matching any of my defined patterns, even though I have a pattern defined for exercise4/int:month/. Can you help me figure out why it's not matching?&quot; <pre class="lang-py …

25.04.2024
Djangos cmd like how do i make my C:\Users\user\Desktop\djangodemo> go into C:\Users\user\Desktop\DjangoCourse\djangodemo>

Enter image description here enter image description here its little different since i had to start another one but i encounter '[Errno 2] No such file or directory' and it has become quite the …

25.04.2024
Filter a query set depending on state at a given date

Given the following model (using django-simple-history): class MyModel (models.Model): status = models.IntegerField() history = HistoricalRecords() I would like to get all instances that didn't have a certain status on a given date (i.e. all instances that …

25.04.2024
Getting django cors error for subdomain but is working on different domain

I've a django app running with gunicorn and nginx. While making request from [ALL https] project.vercel.app to backend.domain.com works correctly. But when i make request from domain.com (Devtools&gt;RequestHeader&gt;Origin : www.domain.com) to backend.domain.com, it gives CORS error &quot;has been blocked by …

25.04.2024
"applicant": [ "This field may not be null."]

Serializers.py from django.core.exceptions import ObjectDoesNotExist from rest_framework import serializers from .models import FieldUser, BaseApplicant, Applicant, CoApplicant, Guarantor class VerificationMobileSerializer(serializers.Serializer): mobile_number = serializers.CharField(max_length=15) class FieldUserSerializer(serializers.ModelSerializer): class Meta: model = FieldUser fields = ['id', 'username', 'first_name', 'last_name', 'email', 'mobile_number', 'profile_photo', 'address', 'pin_code', …

25.04.2024
What is the Bearer token set in Authorization header, why it is so important?

Im using Django-rest-framework where the authorization is being done using bearer access token. The thing is, I want to do auth using the access token stored in cookie storage with HTTP-only. I'm using JWT, How can I handle the auth …

25.04.2024
Am getting this error django.views.static.serve

Am working on my django project , after uploading my file,picture or documents , when i try to download or view a file , I get error django.views.static.serve . my project is django project is connected to postgresql .i expect …

25.04.2024
Django csrf token cannot be read

I am writing a website with Vue as a frontend framework and django as a backend framework. I have included the csrf token in every single request from my frontend to my backend to ensure that I dont get a …

25.04.2024
Python + JavaScript good? [closed]

I learned python and I'm good on python but is python good choice to use it with JavaScript(React + Next.js) And I use Python(Django + FastApi) as a backend lib Is JavaScript(React+Next.js) good with Python(Django + FastApi) as freelancer I …

25.04.2024
How do i accept a list of base64 images in django rest framework

So i am trying to accept multiple base64 images through an endpoint to create a post and this is the object dummie data i want to send. { &quot;user&quot;: &quot;username of the user&quot;, &quot;caption&quot;: &quot;Reasons why my Husky got mad …

25.04.2024
How can I integrate AJAX infinite Scroll with Django View

I have a Django view that originally displays a list of applicants, and using the filter by session, it is expected to display list of applicants by the selected academic session. And using pagination, user is expected to scroll through …

25.04.2024
How do i get the uploaded file from the dropzone hidden input and send it to the socket?

I have a chatting application. I downloaded its template online (HTML, CSS, JS) and It uses Dropzone for file uploads, but I’m having a problem retrieving the file. When I upload the file, it creates a hidden input and previews …

25.04.2024
Configuring django with apache2

I have been working on my first django, which is a portfolio website. The site was working as intended when running on the django server, however when configuring it with apache on the linux server I few things have stopped …

25.04.2024
Build a pre-decorated class with override_settings for faster client.login?

This makes a Django test using the test client run very much faster, where login security is not an important part of the test from django.test import TestCase, Client, override_settings @override_settings( PASSWORD_HASHERS = [ &quot;django.contrib.auth.hashers.MD5PasswordHasher&quot; ]) class Test2(TestCase): ... …

25.04.2024
Trying to connect Django API to my local SQL Server database but it returns the table as empty when testing it in Insomnia

I have an SQL Server database that has mainly 3 tables and I want to create a crud web interface to manage it and I started with creating a Django API for the backend I followed some online guides to …

25.04.2024
'DeferredAttribute' object has no attribute

Im newbie in django.. i dont know why it's raise an error its models.py codes class PublishManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status=Post.Status.Draft) # Create your models here. # First Model class Post(models.Model): class Status(models.TextChoices): Draft = 'Dr', &quot;Draft&quot; Released = 'RL', …

25.04.2024
Views takes the values from template before making the post method

I'm creating a odd one out game. Basically user are presented with four pics , one being the odd one when user selects the odd picture score gets increased by 1. The problem I'm having is I'm sending 4 pics …

25.04.2024
For Django, 'sql_server.pyodbc' isn't an available database backend or couldn't be imported

I'm new to Django and trying to set up a DB Connection with SQL Server db. Earlier we had MySQL which was working fine, I'm having trouble connecting to SQL Server DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'AAAAA', …

25.04.2024
How can I update data in vue.js?

I am new to vue.js and I try to update data. I write this code for pencil icon &lt;i class=&quot;mdi mdi-pencil&quot; v-b-modal.updateHolidayType &gt;&lt;/i&gt; I write this for modal &lt;b-modal id=&quot;updateHolidayType&quot; title=&quot;Update holiday&quot; centered hide-footer&gt; &lt;ModalForm cardTitle=&quot;Update holiday&quot; description=&quot;Update holiday&quot; …

25.04.2024
What is the meaning of this query in django

I am working on a django project, and taking over the project from other developers as they have left the project. I came across a query which I am not able to understand how it works, This is the query …

25.04.2024
Heroku: H18 right before my app should download .mp4

I'm having trouble with my app that generates 5-8sec videos. The entire request takes about 15 seconds, the app does all the steps required, but when it's time to download the video file it fails. I'm deploying the same python …

25.04.2024
When i press edit profile i get value error [duplicate]

Trying to make an edit page where you can upload a profile picture and add various things to your profile, but when i click on edit profile i get &quot;ValueError at /profile/ The 'profile_image' attribute has no file associated with …

25.04.2024
ModuleNotFoundError: Нет модуля с именем 'project_name'

Я попытался создать файл 'load_data.py', но ошибка сбила меня с толку. Traceback (most recent call last): File "/Users/name/Downloads/Dev/culture/culture/api/load_data.py", line 4, in &lt;module&gt; from models import Theatre File "/Users/name/Downloads/Dev/culture/culture/api/models.py", line 4, in &lt;module&gt; class Theatre(models.Model): ... ModuleNotFoundError: No module named …

25.04.2024
Одно раскрывающееся окно со значениями из двух таблиц

Возможно, я делаю это совершенно неправильно. Я новичок в Django, поэтому иногда то, что я думаю о вещах, не похоже на то, что можно сделать с помощью Django. У меня есть две таблицы: class LocationGroup(models.Model): #Fields ##Location Group …

25.04.2024
Django: как хранить учетные данные электронной почты при отправке писем из приложения Django

Какой стандартный или безопасный способ хранения учетных данных электронной почты Google Workspace в моем первом Django-проекте? Я пробовал хранить пароль в файле .env, но получаю всевозможные сообщения об ошибках (например, "модуль decouple не распознан" - несмотря на …

25.04.2024
Перенаправление StreamingHttpResponse в Django

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

25.04.2024
Управление программой искусственного интеллекта с помощью плагина WebODM

Я создал программу AI Python и сделал экран программы видимым через плагин. Я пытаюсь запустить программу, написанную на Python, на этом экране, но она не работает. Как заставить ее работать? Чтобы запустить программу искусственного интеллекта, необходимо запустить Anaconda 3, …

25.04.2024
Как я могу использовать хранимые процедуры в Django с MySQL и запускать 'python manage.py migrate' без проблем?

Контекст: Я работаю над проектом, используя Django с фреймворком Django REST для создания API. Моя база данных - MySQL, а в качестве локальной среды разработки я использую XAMPP. Проблема: Мне нужно использовать хранимые процедуры в моем Django-приложении для …

25.04.2024
Видим желтые линии под django.shortcuts в VS CODE

Я новичок в Django, и я вижу желтые линии под всем, что я включаю из Django, например django.db import models Вижу желтые линии на Django.db и модели также в app.djando Во всех импортированных Django вещах Еда работает полностью нормально, …

25.04.2024
Постоянное хранилище в приложении на Python, размещенном в Heroku

У меня есть приложение, которое я недавно развернул на Heroku. Я написал приложение на Python с использованием фреймворка Django. Когда я создаю учетные записи пользователей через панель администратора в приложении, я вижу их после создания. По прошествии некоторого времени …

25.04.2024
Django default connections.cursor() не разбирает JSONB в DICT, несмотря на использование PSYCOPG3

Я перевожу старую кодовую базу с Django ~2 на Django 4.2.1. Вместе с этим переходом я обновил psycopg2 до psycopg (также известного как psycopg3), но этот переход привел к тому, что мой курсор стал некорректно получать строки из базы …

25.04.2024
Проблема с арабским языком в xhtml2pdf django

Я использую xthml2pdf для создания счета-фактуры на арабском языке. Я много искал, чтобы решить эту проблему и следовал всем шагам, но я не знаю, почему это не работает. Код утилиты: def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) …

24.04.2024
Проблема отсутствия общих обновлений и маркеров доступа для пользователей

У меня проблема с кодом, написанным на Python и фреймворке Django Я написал пользовательскую модель и использовал в ней Abstrcatuser, а вместо поля имени пользователя использовал поле номера телефона. Теперь, когда я ввожу адрес логина в написанном мной api …

24.04.2024
Кликабельная этикетка для радио в django

Я хочу иметь кликабельные метки для моих радиокнопок в django но я не могу нажать и значения не регистрируются в базе данных, это как просто текст &lt;div class="probprior"&gt; &lt;div class="radio-container"&gt; &lt;label for="id_is_observer"&gt; {{register_user_form.is_observer}} Observer &lt;/label&gt; &lt;label for="id_is_technician"&gt; {{register_user_form.is_technician}} Technician …

24.04.2024
Показать два разных столбца в аннотации Django

У меня возникают проблемы с аннотацией в Django. У меня есть две модели в проектах. (только структура) model A (field:name(char)) model B (field:A(A; related_name="b"), user(user), content(char; null=True)) Данные model B такие же, как... row1 -&gt; A:1, …

24.04.2024
Внешний ключ модели Django null=false, но нулевое значение в списке select на форме

У меня есть следующее поле модели: category = models.ForeignKey("QuestionCategory", on_delete=models.CASCADE, null=False, blank=False ) Правильно ли поведение Django, что при выводе в HTML-форму, в списке выбора присутствуют все варианты (все категории), а также "пустой вариант", представленный ----------- (как …

24.04.2024
Два внешних ключа в одной модели

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