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

26.04.2024
Group by or distinct for django to remove the row which has the duplicate column

I have table like this below Table A ID name score 1 aaa 100 2 bbb 200 3 ccc 300 4 bbb 100 5 kkk 600 6 ccc 300 Now name bbb and ccc is duplicated so, I want …

26.04.2024
Passing information from view to form with FormWizard

I'm trying to pass data from my view to my form class using WizardView. Without WizardView, I do this using get_forms_kwargs() like the below: def get_form_kwargs(self): kwargs = super(MenuAdd, self).get_form_kwargs() kwargs.update({'month': self.kwargs['month']}) return kwargs And in my form class …

26.04.2024
Не видит весь проект django а именно в импорте from myapp2.models import Client

''' from django.core.management.base import BaseCommand from myapp2.models import Client class Command(BaseCommand): help = "Create user." def handle(self, *args, **kwargs): client = Client(name='John', email='john@example.com', phone_number="893242", address='secret12', registration_date='25.05.2002') client.save() self.stdout.write(f'{client}') ''' …

26.04.2024
I don't understand why the Django built in 'Reverse' function is not working [duplicate]

I am trying to learn Django in python, when today, I stumbled upon this error: "NoReverseMatch at /downloader/ Reverse for 'login' not found. 'login' is not a valid view function or pattern name." I am not sure why this is …

26.04.2024
A very faulty Django when it comes to rendering image in my template

Right lets try this again. My Django images are not showing in my template. Despite setting this up correctly. This is my setup - a fully replicable setup -, as follows: # settings.py MEDIA_URL = '/media/' MEDIA_ROOT = …

26.04.2024
Bypassing integrityError gotten from unique field in a django model

I want a unique field generated at database level. The way unique=True works is it raises an error if it see's a duplicate value in the database. I don't want that though, I want it to simply generate a new …

26.04.2024
In django how can I resolve a reverse error when copying text from an html table row and attempting to write it to a text file?

I have a django app with a page that shows a data table of text strings populated from a model. Each string is a website url. I need to be able to click on any one of these rows and …

26.04.2024
Why do I get a server side HTTP 400 error when I try to access my django server with my mobile phone?

I have set up a simple, local running django server which provides buttons to trigger some bash commands on the server (currently my MacBook Pro). The output of these commands is then displayed on the website. Anyways: The website is …

26.04.2024
Management.call_command как запустить из отдельного .py файла

Пытаюсь выполнить тестирование management функции Django, если я вызываю команду из консоли: python3 manage.py read_all_news - работает как ожидается, но при попытке вызвать команду внутри функции в файле testing.py - выдает ошибку, что команда не найдена. testing.py from django.core import …

26.04.2024
"Error: InconsistentMigrationHistory - Django migration admin.0001_initial applied before its dependency Users.0001_initial" [duplicate]

I am encountering an error while running `python manage.py migrate` in my Django project. The error message is as follows: It appears that there is an inconsistency in the migration history of my Django project. Specifically, the `admin.0001_initial` migration is …

26.04.2024
Django-tables2 linkify to other app of project: TemplateDoesNotExist error

Since my project is a bigger one, I have several apps with each app having some database tables (with each table in its own file): project --project -all -overview -home In all/probe_list.html I have a table which displays …

26.04.2024
PostgreSQL: How to tag every table in my database? Generic Foreign Keys, array column, or other method

I'm currently designing a PostgreSQL database where I need to implement a tagging functionality. Essentially, any item from any table in my database can be tagged via key-value tags, very much like Azure tags. I'm considering different approaches for implementing …

26.04.2024
How do I setup "Django" to generate multiple 'STATIC_ROOT' deployment directories in its settings.py?

Here's the problem, when migrating multiple 'STATICFILES_DIRS', I am good to go, and the server continues to run with no errors... ... Here's the snippet to my 'STATICFILES_DIRS' ... ... STATIC_URL = 'Application/' #Multiple Static Directories STATICFILES_DIRS = [ os.path.join('Application', …

26.04.2024
Create SQL function using Django migrations command

I am using Django Framework in Python with MySQL Database. For adding a table in the database, I create a class in models.py and then run python manage.py makemigrations. This creates the migration file in my app with the table …

26.04.2024
How do I update status to either expired or active depending on date and time?

I have an application built in Django. The application allows businesses to manage their day-to-day operations and has features like; HR Management, Sales, Point of Sale, Accounting, etc. For businesses to be able to attach discounts on their products, I …

26.04.2024
Provider in create Social App in Django Administration is blank

I tried to do google auth in Django but got stuck when there wasn't any provider in the create social app i already creates the sites as my local host and tried changing site Id to 1 and 2 still …

26.04.2024
Trouble running react-google-drive-picker in Django

I'm attempting to implement a google drive picker in my django + react project: import React from 'react'; import { Button, Card, Image } from 'antd'; import useDrivePicker from …

26.04.2024
How to ignore the get_valid_name to sanitize the space and special characters

When we are uploading the files to azure storage via django, it's adding underscore if space or special characters are there in the filename and it's disturbing the functionality. Is there anyway we can ignore it or change it. I …

26.04.2024
How to connect htmx with webstocket

I am building a real-time chatroom using htmx connect with webstocket in Django, when I try to send a message, the message is not showing and I am getting this error in the terminal "HTTP GET /?csrfmiddlewaretoken=frNekEsvdZ6jdJp7gYMF7pvXpnO11m3J3vOpJ7XCsAKLogIBuUpuKizmufpWRKxN&body=hi+aneeb 200 [0.04, 127.0.0.1:54773]" …

26.04.2024
Django Language cookie issue [closed]

I'm trying to enable the secure and HttpOnly flags to the django cookies but not able to add it for the django_language. I have configured the following var in the settings file: CSRF_COOKIE_SECURE = True ### enabled secure flag CSRF_COOKIE_HTTPONLY …

26.04.2024
How to implement voice activity detection and stop Twilio voice bot on customer interruption?

I am building a voice bot using Twilio and Django. I have set up an outbound call with media streaming, which is working fine. However, I want to implement voice activity detection so that if the customer interrupts while the …

26.04.2024
Django models cannot be queried due to missing id field?

I currently am working on a django project for a discord bot. the issue that I am trying to resolve is that I cannot seem to query the data for one of my models. A piece of information that has …

26.04.2024
How do I ensure my API can't process the same method simultaneously

I have a method in my API that handles the sync operations with the company's ERP. This method is called once every 30 minutes by a script I made to ensure that everything will be always up date. However, if …

26.04.2024
Django. Объединение полей ManytoMany для последующей сортировки

Подскажите пожалуйста, есть два класса Book и Author. У книги может быть как много авторов, так и ни одного. class Author(models.Model): name= models.CharField() class Book(models.Model): title = models.CharField() author = models.ManyToManyField(Author, blank=True) Соответственно требуется объединить значения полей …

26.04.2024
ChatConsumer() missing 2 required positional arguments: 'receive' and 'send', what's the mistake?

I can't understand why I'm getting an error. I've tried different approaches, but I still encounter an issue with consumers.py. What's the problem, and what am I doing wrong? messaging_users/routing.py from django.urls import path from channels.routing import ProtocolTypeRouter, URLRouter from …

26.04.2024
Django Static files Permission Issue on nginx

I want to deploy my Django project on linux vps but i have a problem and the problem is my nginx denies the permission for opening the static files i found this error in error.log file: open() "/home/sam/testdjango/static/admin/js/nav_sidebar.js" failed …

25.04.2024
I am getting a no such column error only when running tests

Perhaps this is leaving out some key detail and exposing my relative newness to django, but I tried to isolate my issue to the fewest steps to reproduce the problem. Starting state: App running fine, tests all passing. Add …

25.04.2024
Why is django class-based_view not seeing my uploads?

Class MultipleFileInput(forms.ClearableFileInput): """ Work around for `widget=forms.ClearableFileInput(attrs={'multiple': True})` >> `widget=MultipleFileInput(attrs={'multiple': True})` """ input_text = 'Select' clear_checkbox_label = 'Clear' initial_text = 'Current' allow_multiple_selected = True class UserUploadForm(forms.ModelForm): file = forms.FileField( widget=MultipleFileInput(attrs={'multiple': True}), required=True, validators=[FileExtensionValidator(allowed_extensions=['csv'])], ) class Meta: model = UserUpload fields …

25.04.2024
Filtering DataFrames in a Django Dashboard

I am trying to build a Dashboard with Django... I wish to filter the dashboard with category, month and Year. The dataFrame is coming from python code than I am adding the charts with JS. I don't know how to …

25.04.2024
Raise ImproperlyConfigured("SECRET_KEY setting must not be empty")django.core.exceptions.ImproperlyConfigured:The SECRET_KEY setting must not empty [duplicate]

I published my Django project into github and I had a lot of variables that stored in .env for secure. And when anyone clone that project and migrate its not reading variables in my .env file that saved in .gitignore. …

25.04.2024
Html button not work on each click - hot to debug it? (chrome)

I've got a (django) app, that displays a page with videojs-record, with ability to record something and send to backend. In general both recording and sending works fine. But - after recording there is a button to send (button with …

25.04.2024
How do I display the list items on the site as links

This is my question and I'm just starting to learn django ^-^ these are urls from django.urls import path, include from . import views urlpatterns = [ path('', views.index), path('<int:days_week>/', views.get_info_week_intoviy), path('<str:days_week>/', views.get_info_week, name = 'day-week'), path('type/', views.teplt, name='types'), ] …

25.04.2024
I keep on getting GET http://127.0.0.1:8000/room/f5428fc5 404 (Not Found):

Im making a Next.js and Django full stack app with Spotify api, and Im having trouble fetching the get-room api, when ever I click on the button to create a room in the create.js page the room is created and …

25.04.2024
Я хочу связать мою подкатегорию с соответствующей категорией в forms.py. Как это сделать?

В настоящее время я работаю над проектом на Python, где я пытаюсь получить категорию из связанных с ней подкатегорий. Однако я столкнулся с проблемой, когда поле подкатегории ничего не показывает. Есть 4 файла, которые я загружаю: This is models.py …

25.04.2024
Django не получает доступ к базе данных PostgreSQL с помощью Docker

Вот сообщение об ошибке: 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 Вот моя .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
Сериализация вложенного объекта с помощью Django Rest Framework

В настоящее время я пытаюсь сериализовать следующий объект в перечисленные ниже модели, текущее отношение Категория имеет много викторин, викторина принадлежит одной категории, но содержит много вопросов, вопрос принадлежит викторине, но содержит много вариантов ответа. Любая помощь будет очень …

25.04.2024
Я не могу перенаправить мое приложение django с int на string в url

У меня проблемы с шаблонами URL в Django. URL exercise4/1/ не соответствует ни одному из моих определенных шаблонов, хотя у меня есть шаблон, определенный для exercise4/int:month/. Не могли бы вы помочь мне выяснить, почему он не соответствует?" <pre class="lang-py …

25.04.2024
Djangos cmd, как мне сделать так, чтобы мой C:\Users\user\Desktop\djangodemo> перешел в C:\Users\user\Desktop\DjangoCourse\djangodemo>.

введите описание изображения здесь введите описание изображения здесь немного отличается, так как мне пришлось начать другую, но я столкнулся с '[Errno 2] Нет такого файла или каталога' и это стало довольно большой …

25.04.2024
Фильтруйте набор запросов в зависимости от состояния на заданную дату

При следующей модели (с использованием django-simple-history): class MyModel (models.Model): status = models.IntegerField() history = HistoricalRecords() Я хотел бы получить все экземпляры, которые не имели определенного status на заданную дату (т.е. все экземпляры, которые имели …

25.04.2024
Получение ошибки django cors для субдомена, но работает на другом домене

У меня есть приложение django, работающее с gunicorn и nginx. При выполнении запроса с [ALL https] project.vercel.app на backend.domain.com работает корректно. Но когда я делаю запрос с domain.com (Devtools&gt;RequestHeader&gt;Origin : www.domain.com) на backend.domain.com, он выдает CORS ошибку "has been …