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

19.04.2024
Referencing a foreign key field attached to another model in a Django filter

I have a Profile model which is related to the Django User model via a 1:1 relationship. In the profile model is a field "nickname." I am filtering a table with a foreign key to the User model but want …

19.04.2024
Django + Frontend Framework: SEO, rendering strategy, user experience and familiarity

I'm a new full-stack developer comfortable with Django and looking to build a few new web applications this year. While Django offers templating, I'm considering using a separate frontend framework like Vue.js for enhanced user experience. However, I'm unsure about …

19.04.2024
How to properly use TailwindCSS with Django forms

I'm trying to use TailwindCSS in my Django project and can't find a way to cleanly style forms. There are a ton of ways on the internet, but all of them seem a little bit dirty. The way styling is …

19.04.2024
Django save override only if anything other than a single field is updated?

I realize a version of this has been asked and answered, but I believe my question is slightly different enough where I could not find an answer. I have a model with a version that I want to increment by …

19.04.2024
Как привязать обьект Django models к JavaScript?

Мне нужно передать данные из django.models в JS для их дальнейшей обработки. JS скрипт я могу разместить в самом html, но мне нужно, чтобы было наглядное разделение JavaScript от HTMl. Поэтому я добавляю скрипт в html через src. Однако, если …

19.04.2024
Request.user.is_authenticated does not work in templates

When using {%if request.user.is_authenticated%} or {%if user.is_authenticated%}, nothing happens because of what it can be? And for some reason, the check for user.is_admin or user.is_staff does not work. footer.html: {% if request.user.is_authenticated %} <li class="footer__widget--menu__list"><a class="footer__widget-- menu__text" href="#">My Account</a></li> {% …

19.04.2024
Django NOT NULL constraint failed: TourSite_books.user_id

Вылетает вот такая ошибка: пробовал вот такой способ решения (views.py): order = form.save(commit=False) order.user = request.user order.save() Вот фрагменты кода: models.py class Books(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) tour = models.ForeignKey(Tours, on_delete=models.CASCADE, default=None) …

19.04.2024
How can I render tag set in my django template

I'm trying to render tags from a many to many relationship but I'm missing something These are my models: class Post(models.Model): date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='posts', null=True, blank=True) title = models.CharField(max_length=200) content = models.TextField(null=True, blank=True) image = …

19.04.2024
Uploading a python file in a django admin dashboard to excecute an excel file

I'm a beginner working on a django project, django admin dashboard, using mysql database, one of the tasks is uploading an excel file and execute it with a python file then showing the result. there are 3 types of python …

19.04.2024
Django Autocomplete Light Foreign Key not rendering

I believe I have tried everything but still my field is not rendering. My objective is to be able to find products writing their names. I tried to followed this tutorial: https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html#tutorial My diferent files are like …

19.04.2024
Django - Unit test RuntimeError model class doesn't declare an explicit app_label

Heyo all. I'm having an issue running unit tests in my new Django project. Whenever I try running them inside PyCharm, I am getting the error: ImportError: Failed to import test module: backend.dtva_app.models Traceback (most recent call last): …

19.04.2024
Internal server error in Elasticbeanstalk after deployed my Django webapplication

This is the log data from Elastic beanstalk after deployed my Django web application here are ImportErrors indicating that libGL.so.1 cannot be found, which is causing issues when importing cv2 in your Django views. How to resolve this error ? …

19.04.2024
Docxtpl duplicate render data in for loop

I have an API in Django Rest Framework and encountered an issue with docxtpl. I'm using a template to be filled by a single render with a global context, converting the file to PDF, and sending it to my frontend …

19.04.2024
How to retrieve the GeoDjango Point model lat and lon coordinates in Django values_list of objects

Would like to retrieve the GeoDjango Point model lat and lon coordinates from a values_list of objects. I'm only able to retrieve a full descriptive string such as "SRID=4326;POINT (1 1)". I need to just retrieve the lat and long …

19.04.2024
Modal button click function not defined - Uncaught ReferenceError

Question Description: I have a modal that should open when clicking on a &quot;Share!&quot; button on my webpage. However, I'm encountering an &quot;Uncaught ReferenceError: openShareModal is not defined&quot; error. Below are the relevant parts of my code: Modal Code: <pre …

19.04.2024
In Django, Update a different table at the time of saving a record from one table

My tables are: models.py class Warehouse(models.Model): site_name = models.CharField(max_length=100) class Item(models.Model): item = models.CharField(max_length=100) class WarehouseStockStatus(models.Model): site_name = models.ForeignKey(Warehouse, on_delete=models.CASCADE) item = models.ForeignKey(Item,on_delete=models.CASCADE,editable = False) class Meta: unique_together = ((&quot;site_name&quot;, &quot;item&quot;)) stock_opening_quantity = models.PositiveBigIntegerField( default = 0, editable = …

19.04.2024
Invalid HTTP_HOST on Django (EC2 Aws Ubuntu)

I'm having trouble deploying my Django application. I'm running it using nohup on port 8000 and using nginx with SSL certificate configuration, masking the domain to port 80. Here are my default Nginx settings: server { listen 80; listen 443 …

19.04.2024
Running a Celery server and Django server individually on the same AWS EC2 instance?

I can successfully run a django server on my EC2 instance with Ubuntu on AWS, as well as the celery server. However, unlike in my Visual Studio Code editor where I can create multiple terminals and have each one run …

19.04.2024
Django djfernet "TypeError: string argument without an encoding" [closed]

I am experiencing the error only in a few environments with the same version of the libraries, as follows: djfernet 0.8.1 django 4.2.11 Python 3.9.18 I'm reading data from a form in Django and I'm getting in the console: File …

19.04.2024
Custom primary keys break Django admin inlines logic

I have a model with self relation in models.py: from uuid import uuid4 from django.db import models class Example(models.Model): uid = models.UUIDField(primary_key=True, default=uuid4) title = models.CharField(max_length=128) parent = models.ForeignKey(&quot;self&quot;, related_name=&quot;subexamples&quot;, blank=True, null=True) and Django admin models: from .models import …

19.04.2024
Django/Heroku - Custom 500 template

I have a template defined and loaded on S3. The template has been granted public access. The template is referred in Heroku as variable ERROR_PAGE_URL and the S3 link is attached against this variable. Somehow the template is not displaying …

19.04.2024
Exception Value: User matching query does not exist [closed]

DoesNotExist at /profile/username User matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/profile/username Django Version: 5.0.4 Exception Type: DoesNotExist Exception Value: User matching query does not exist. Exception Location: D:\Django projects\social media app\social_media_app_env\Lib\site-packages\django\db\models\query.py, line 649, in get Raised …

19.04.2024
Django populating a form on a modal

I have a problem with populating a form on a modal pop up. I can get a form added to the modal, but I want it to be based on the line a user clicks on. My view: class SalesQuotationDetailView(LoginRequiredMixin, …

19.04.2024
HEROKU (Dockerfile that does not exist)

Tried hosting my django website on Heroku, but keeps getting dockfile does not exist which is from the heroku.yml file Waiting on build... Waiting on build... (elapsed: 6s) Waiting on build... (elapsed: 9s) === Fetching app code =!= There were …

19.04.2024
Two detail tabels with a foreign key to the same master table (User), how to limit a ManyToManyField to see only the subset of the other detail tabel

In Django I have an Order and Contact table that both have a foreignKeyField to the User table, in the Order table I want a ManyToManyField to see only the subset of Contact table records that belong to the same …

19.04.2024
Django Project CORS error after deployment

I got Pyton Django project and my project work on local server but when i deploy on server i got this error.I used IIS Manager for deployment.Other DB connection must be work because i can reach other APIs.By the way …

19.04.2024
I have a Category model and a subCategory model and a product model which has foreign key with category and sub category

I have a Category model and a subCategory model and a product model which has foreign key with category and sub category . Whenever a client will add a product then he will select a category and according to that …

19.04.2024
Django Channels on IIS using FASTCGI

I am deploying a Django app using an IIS server. In this Django app, I have implemented Django Channels to use websockets. Locally, everything is working fine with websocket connections, and I am able to send messages. However, the issue …

19.04.2024
How to set default value of a model field to another field of same mode in django

I've created a Student model in django project with has a field named &quot;enrollmentdate&quot; and &quot;paymentdate&quot; now i need to save &quot;paymentdate&quot; as default value in &quot;enrollmentdate&quot; my model code is as under, &gt; ``` class Student(models.Model): fname = models.CharField(max_length=100) …

19.04.2024
Django serializer

This serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'password'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): #user = super(RegisterSerializer, self).create(validated_data) user = User.objects.create_user(**validated_data) return user and Loginserializer : <pre class="lang-py …

19.04.2024
Django " [ was not closed " error in url routing [closed]

I'm new to python. Trying to understand and following the tutorials. One of the many tutorials that I follow, in django for url routing we are creating url.py and put our routing logic inside that file as below: urlpatterns = …

19.04.2024
Django string interpolation struggles [duplicate]

Hi so I am having a problem trying to concatenate in django. I have created a new templatetag and im trying to get the string interpolation right and im struggling a bit. {% button text=&quot;Reset&quot; onclick=&quot;test('{{user.id}}')&quot; colour=&quot;yellow&quot; %} function test(user_id){ …

18.04.2024
Django. Как показать разновидность товара?

При создании интернет-магазина возник вопрос: как отображать такой же товар, только другой модификации? Допустим, у меня есть корм для собак с лососем 0.4кг, также есть такой же товар, только с индейкой на 0.6 и 0.8кг. Как производить фильтрацию и отображать …

18.04.2024
Почему разрешения не переопределяются для набора представлений?

Я создал набор представлений для аутентификации. Поскольку это набор представлений для аутентификации, я хочу, чтобы этот набор представлений был доступен и для неавторизованных пользователей. Следуя документации DRF, вот что у меня получилось: class AuthenticationViewSet(viewsets.ViewSet): permission_classes = [AllowAny] def create_user(self, …

18.04.2024
Объект django 'NoneType' не имеет атрибута 'userprofile' Проблема в связанных файлах

Hi у меня есть проект django и у меня есть связанная база данных я не могу получить два файла из базы данных и появляется вышеуказанная ошибка и это models.py для отображения приложения class Display(models.Model) : url=models.URLField(unique=True) text = models.CharField(max_length=150) class …

18.04.2024
Пишу на Django, хочу в моделях сделать пункт size чтобы он был с некоторым количеством полей

Например: чтобы было 5 полей и все они были необязательные. Чтобы именно один пункт отвечал за эти 5 полей, а не несколько пунктов с необязательным заполнением поля. Можно ли это реализовать?

18.04.2024
Django 5.0: Как создать объект без получения экземпляра объекта Foreign, связанного с ним?

В настоящее время у меня есть несколько моделей Django, определенных следующим образом: Class Project(models.Model) data = ... Class Resource(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) В моем views.py я пытаюсь создать новый ресурс, имея доступ к идентификатору проекта благодаря URL: …

18.04.2024
У меня проблема с добавлением продукта пользователем для системы онлайн-аукциона, над которой я работаю для своего выпускного проекта? [закрыто]

Я работаю над своим выпускным проектом, который представляет собой систему онлайн-аукциона. У меня возникла проблема с добавлением товара на аукцион вошедшим пользователем, а также проблема с обновлением профиля и удалением пользователя. Используется Django react tailwind. Здесь представлены все …

18.04.2024
Как решить эту проблему в django?

[18/Apr/2024 19:33:24] code 400, message Bad request version ('¼%-¼Iµ\x19\x87)Û\x81AWf;eÓÒNøíýg§\') [18/Apr/2024 19:33:24] Вы обращаетесь к серверу разработки по HTTPS, но он поддерживает только HTTP. я изменил настройки http с true на false, но он продолжает настаивать

18.04.2024
Как решить ошибку ModuleNotFoundError в коде django

Я разрабатываю webtool с помощью django. Я уже установил и активировал виртуальную среду. Я получаю следующую ошибку, которую, похоже, очень легко исправить: from .views import ( File "/home/example/views.py", line 8, in &lt;module&gt; from subscriptions.models import Subscription ModuleNotFoundError: No …