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

28.04.2024
ModuleNotFoundError: No module named 'django.db.backends.postgresql' on Ubuntu 24.04

Yesterday I switched to Ubuntu 24.04 LTS from windows and having an issue with my django project and tried every suggestion on the web but no luck. I'm getting below issue: django.core.exceptions.ImproperlyConfigured: 'django.db.backends.postgresql' isn't an available database backend or couldn't …

28.04.2024
Передача данных из localstorage в views в Django

У меня есть функция добавляющая данные в localstorage ключ: cart; поля: name, price, image, quantity и есть страница с оформлением заказа: пользователь заполняет форму где указывает имя, фамилию, номер телефона и адрес электронной почты. Я хочу чтобы после нажатия кнопки …

28.04.2024
Django/Heroku - Handling ObjectDoesNotExist Exception When Pushing Data from API to Django Database

My django application receives data from an API. It's very unlikely the API will send incorrect information, but I am trying to cover the possibility the API may send data that would return ObjectDoesNotExist from malicious attempts. Below is my …

27.04.2024
Cannot get response for more than first or several first requests with Django and Apache?

I have started to learn Python, then Django in practice by way of executing tutorial codes in Python IDLE. Indeed as maybe the code is of old versions the code running not always works well. Especially I am stacked upon …

27.04.2024
Django celery media folder backup issue

I create a library to get backup to Google Drive using with Google Drive api in python. Actually its work well but when I use with celery my library, celery do not wait for compress my media folder(I guess). Its …

27.04.2024
Django update m2m objects on save

I have a m-2-m rel and i want to update the rel B after any rel A is added via the admin page. Here the details: I have 2 models, Match (rel A) and Player (rel B). I want to …

27.04.2024
Media not shown on django nginx host

I am currently working on a django project which I deployed to a digitalocean droplet with nginx. The website works, including the staticfiles. After looking at my error.log i saw that it was a permission problem: 2024/04/27 18:58:19 [error] 130139#130139: …

27.04.2024
Django unit test fixing database row id

From django.test import TestCase class DefTests(TestCase): def setUp(self): # first made the label UserType(label="mylabel").save() ## UserType is model object, and I made the first row , the id is supposed to be 1 def test_my(self): u = UserType.objects.get(id=1) # UserType.DoesNotExis …

27.04.2024
Django Rest Framework serializer simultaneously request bug

I have one view with my basics config class base_view(LoginRequiredMixin, PermissionRequiredMixin): filter_backends = [SearchFilter] pagination_class = generic_pagination permission_required = '' # assigned at each final view (children) raise_exception = True # avoid redirecting to backend login fields = '__all__'# by …

27.04.2024
Django - how to distinguish code is run by manage.py or but http server

I customized AppConfig in django to start some processes needed for the main application as described in the django documentation. In the usual initialization process, the ready method is only called once by Django. But in some corner cases, …

27.04.2024
Using my trained model in the views, don't allow me to render the new return valus

It takes a while to load all the data into the new df_with_ṕredictions, my problem is how can I render the new table with those predictions in a template : def home(request): df = None df_with_predictions = None …

27.04.2024
Enabling cache and images not loading in django?

If you enable the cache: @cache_page(20, key_prefix='index_page') def index(request): post_list = Post.objects.order_by('-pub_date').all() paginator = Paginator(post_list, 10) page_number = request.GET.get('page') page = paginator.get_page(page_number) return render(request, "index.html", {'page': page, 'paginator': paginator}) When I create a new post, I can no longer …

27.04.2024
ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value cant migrate python file

I am not able to migrate my changes. when i run python manage.py runserver - Full Traceback Traceback (most recent call last): File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\manage.py", line 22, in main() File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\core\management_init_.py", line 442, in …

27.04.2024
CSS is not visible [closed]

I'm working on a project using Django. I imported HTML files and created a Base HTML. I placed CSS and images in a folder named 'static' and imported them, but the CSS is not appearing on the site, only the …

27.04.2024
Django Form's HiddenInput does not save initial value

I have a simple form with two HiddenInputs. Submitted form does not save initial values for hidden fields. What am I missing? forms.py class TestForm(forms.Form): foo = forms.CharField(required=False, initial="Foo") bar = forms.CharField(required=False, initial="Bar", widget=forms.HiddenInput()) is_true = forms.BooleanField(required=False, initial=True, widget=forms.HiddenInput()) …

27.04.2024
Getting error while running Django app on apache2 server about GOOGLE_CLOUD_PROJECT

I am facing an issue while deploying my Django app on apache2 sever. Project ID is required to access Cloud Messaging service. Either set the projectId option, or use service account credentials. Alternatively, set the GOOGLE_CLOUD_PROJECT environment variable. I have …

27.04.2024
Create Razorpay Order in my Django DRF project gives 401 Error. "Authentication credentials were not provided."

Im trying to create a view where we create an order through razorpay, but continuously getting 401 error despite the keyId and KeySecret being correct. Even postman and curl gives the same error. I have tried removing the authentication, adding …

27.04.2024
Django render a view depending geolocation from the browser

I'm trying to load my home page according to the geolocation given by the browser, if the coordinates are ok, I load a list of airports around these coordinates, otherwise I load all airports. However, I can't manage this between …

27.04.2024
How to set custom JWT in django using dj-rest-auth

I have setup a backend JWT authentication system using django, dj-rest-auth and simpleJWT. Currently, the dj-rest-auth is setting default JWT in the response cookies. To use custom cookies, I have to use simpleJWT's /token and /token/refresh urls. So, while testing …

27.04.2024
I keep getting these errors "GET /static/style.css HTTP/1.1" 404 179 , "GET / HTTP/1.1" 200 10881 , Broken pipe from ('127.0.0.1', 57644)

STATIC_URL = '/static/' STATICFILES_DIRS = ((os.path.join(BASE_DIR, 'static')), ) STATIC_ROOT = os.path.join(BASE_DIR, 'files') STATIC FILES_FINDERS = [ > > "django.contrib.staticfiles.finders.FileSystemFinder", > > "django.contrib.staticfiles.finders.AppDirectoriesFinder", > > ] urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('paintings/', views.paintings, name='paintings'), path('sculptures/', views.sculptures, name='sculptures'), path('engravings/', …

27.04.2024
Django: no access to database from async function

I am writing tests for my Django application using asyncio and running into a database access issue. Here is minimal code that reproduces the error: import pytest from authentication.models import User @pytest.mark.django_db(transaction=True) @pytest.mark.asyncio class TestDatabaseAccess: @pytest.fixture(autouse=True) def _fixture(self): User.objects.create(username='username') async …

27.04.2024
Creating two separate models for patient and doctor using Django

I want to create registration as a patient and as a doctor such that when user login my website they get two options(as patient or as doctor).How to achieve this using Django? Registration form has different fields for Doctor and …

27.04.2024
Django Ñ problem? ValueError: source code string cannot contain null bytes

I'm working on Django and connecting to a remote SQL Server database. I managed to make the connection to the database using the MSSQL engine, but when I run inspectdb, the generated file contains errors due to the character "Ñ", …

27.04.2024
When posting on django website it posts it to a different page

Making a website that has a forum for text posts and a greenhouse page for images, when I try to post on the forum page it posts it to the greenhouse page, and when i try to add a comment …

27.04.2024
Django / python, дублируются запросы на сервер

Я неопытный кодер и впервые пишу большой сайт на django, возникла проблема, я динамически загружаю контент в различные блоки/секции (одна страница, контент меняется), и при любом действии дублируется запрос, нажал на кнопку которая выводит в консоль 1 сообщение выводится 2, …

27.04.2024
Can I add the controller part of the MVC pattern to the MTV pattern in Django?

I'm trying to develop a multiplayer web game using Django. I understand that in Django's MTV Pattern, the view part takes on the role of the controller. But the view part needs a user in the frontend who accesses the …

26.04.2024
Проблема с запросами к внешним ресурсам из приложения Django

UPDATE: Оставляю изначальное сообщение без изменений, дополнение ниже после "UPDATE" Пишу свое первое Джанго-приложение, появилась необходимость получить данные о транзакции в сети BSC по ее хэшу. Как водится, спросил совет у ChatGPT, он надоумил на следующее: checker.py (это я создал …

26.04.2024
Calling python package by package name

I want to call my local package utility by its name like in Django django-admin. It has structure like: utility-name [command] I've found the method of calling utility using __ main __.py. Structure of using this method is: python -m …

26.04.2024
Enabling cache and images not loading in django? [закрыт]

If you enable the cache: @cache_page(20, key_prefix='index_page') def index(request): post_list = Post.objects.order_by('-pub_date').all() paginator = Paginator(post_list, 10) page_number = request.GET.get('page') page = paginator.get_page(page_number) return render(request, "index.html", {'page': page, 'paginator': paginator}) When I create a new post, I can no longer …

26.04.2024
Why do I get a Integrity Error when using this code in Django?

I am having issues while learning about SQLite databases in Django. I am trying to check if a specific url is already in the database, but I keep getting a Integrity Error. this is the code that is supposed to …

26.04.2024
Django can not create a filed although i make makemigrations and migrate

Hi i have a filed i cannot make it in database although i make makemigrations and migrte this is models.py class Display(models.Model) : url=models.URLField(unique=True) text = models.CharField(max_length=150) class Display_Data(models.Model) : displays = models.ManyToManyField(Display,related_name='display_data') users= models.ForeignKey(UserProfile,on_delete=models.CASCADE,default="1") choosenum=models.IntegerField() puplish_date =models.DateTimeField(default=datetime.now) and …

26.04.2024
I am getting NoReverseMatch error when adding students data in django admin panel

I am a beginner and trying to create a basic college portal. I am getting NoReverseMatch at /admin/api/student/add/ error when adding students data in django-admin panel. urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/',admin.site.urls), path('api/',include('api.urls')), …

26.04.2024
Группируйте по или различайте, чтобы django удалил строку, в которой есть дублирующийся столбец

У меня есть таблица, как показано ниже Таблица A ID name score 1 aaa 100 2 bbb 200 3 ccc 300 4 bbb 100 5 kkk 600 6 ccc 300 Теперь имена bbb и ccc дублируются, …

26.04.2024
Передача информации из представления в форму с помощью FormWizard

Я пытаюсь передать данные из моего представления в класс формы с помощью WizardView. Без WizardView я делаю это с помощью get_forms_kwargs(), как показано ниже: def get_form_kwargs(self): kwargs = super(MenuAdd, self).get_form_kwargs() kwargs.update({'month': self.kwargs['month']}) return kwargs А в классе …

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
Я не понимаю, почему встроенная в Django функция 'Reverse' не работает [дубликат].

Я пытаюсь изучить Django на python, и сегодня я наткнулся на эту ошибку: "NoReverseMatch at /downloader/ Reverse for 'login' not found. 'login' не является правильной функцией представления или именем шаблона." Я не уверен, почему это происходит, но вот …

26.04.2024
Очень плохой Django, когда дело доходит до рендеринга изображения в моем шаблоне

Правильно, давайте попробуем еще раз. Мои изображения Django не отображаются в моем шаблоне. Несмотря на правильную настройку. Вот моя установка - полностью воспроизводимая установка - выглядит следующим образом: # settings.py MEDIA_URL = '/media/' MEDIA_ROOT …

26.04.2024
Обход ошибки integrityError, полученной от уникального поля в модели django

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

26.04.2024
Как в django решить обратную ошибку при копировании текста из строки html-таблицы и попытке записать его в текстовый файл?

У меня есть приложение django со страницей, которая показывает таблицу данных с текстовыми строками, заполненными из модели. Каждая строка - это url сайта. Мне нужно иметь возможность нажать на любую из этих строк и записать строку url в текстовый …

26.04.2024
Почему я получаю ошибку HTTP 400 на стороне сервера, когда пытаюсь зайти на свой сервер django с мобильного телефона?

Я создал простой, локально работающий сервер django, который предоставляет кнопки для запуска некоторых команд bash на сервере (в настоящее время это мой MacBook Pro). Вывод этих команд затем отображается на сайте. В общем: Веб-сайт работает нормально, пока я …