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

28.03.2024
How to configure django 5.0.3 to be able to use private/public media files on AWS - s3

Today I feel very frustrated , after 3 days trying to implement django using amazon s3 with media file in private mode. In the past my apps has been configured using the following link bellow and always work fine: <a …

28.03.2024
How notification works [closed]

Need an notification when a registration is complete or a new user is created on user side.This notification is shown in admin side.This is a REACT project and the backend is provided through django REST Api. I created a seperate …

28.03.2024
Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response, nginx, django, waitress

I'm using nginx server to serve static React js files and waitress server for django rest framework with 0.0.0.0:8000 as address to serve api's. I'm using nginx as a reverse proxy for django. Even though i have modified django setting …

28.03.2024
Migrate error : ...No migrations to apply

I made some changes in the models from my apps and then entered makemigrations and migrate in the terminal. PS C:\Users\USER 1\frist project\website&gt; python manage.py makemigrations home No changes detected in app 'home' PS C:\Users\USER 1\frist project\website&gt; python manage.py migrate …

28.03.2024
Edit Form in Modal Window Django

I am trying to do an Edit form in the modal window. The problem is that I cannot pass the form into the modal window and show the modal. I tried to do it with HTMX but it is not …

28.03.2024
Reading IPTC information Django

I have published my django project on shared hosting, there are no problems at all. Everything seems to work as it should, but as soon as the system is to read IPTC information from images, it does not work. I …

28.03.2024
Dropzone inside a Django form

I'm trying to make a django form in which I want to upload a photo (Dropzone) and enter its title. I can't send the title field and the photo to my view at the same time. Could you please help …

28.03.2024
Django queryset remains empty initially but populates after creating an object without re-running the query. How is this possible? [duplicate]

I'm encountering a perplexing issue in my Django application. I have a queryset (qs) obtained from a database query at the beginning of a DRF api call. Strangely, this queryset appears empty upon inspection. However, as I continue through the …

28.03.2024
Need help in optimizing the seriliazer

I have the following model ProductCategory. class ProductCategory(Model): name = CharField(max_length=200) parent_category = ForeignKey( &quot;ProductCategory&quot;, related_name='child_categories', on_delete=CASCADE, blank=True, null=True, ) is_base_category = BooleanField(default=True) I have the following ProductCategorySerializer. class ProductCategorySerializer(serializers.ModelSerializer): children = serializers.SerializerMethodField(read_only=True) @staticmethod def setup_eager_loading(queryset): # Prefetch for …

28.03.2024
Cassandra: "Model keyspace not set" and "Connection name doesn't exist in the registry" Errors

I recently upgraded to Django 4.2 and am facing issues with Cassandra integration. Initially, I encountered the following error when attempting to generate queries: cassandra.cqlengine.CQLEngineException: Model keyspace is not set and no default is available. Set model keyspace or setup …

28.03.2024
Django Deployment on AWS EC2 with Docker Compose: Seeking Advice on Security, Scalability, and Best Practices

I am currently working on deploying a Django application to an AWS EC2 instance using Docker Compose. The setup involves containerizing both the Django app and NGINX, with AWS RDS utilized for the database. Additionally, there's a Redis service planned …

28.03.2024
Django: FieldError: Cannot resolve keyword 'name' into field. Choices are: Name, id

Just get started with Django. I was following this tutorial:Django Tutorial Part 3: Using models, and I encountered this issue at the linked step python3 manage.py makemigrations python3 manage.py migrate After executing the second command …

28.03.2024
I don't understand which databases are invalid

I'm getting the following data: {'name_work': 'рациональные числа', 'writing_date': datetime.datetime(2024, 3, 15, 16, 18, 37, tzinfo=datetime.timezone.utc), 'student_type': &lt;TypeStudentWork: TypeStudentWork object (2)&gt;, 'number_of_tasks': '10', 'student': &lt;User: Dear Student&gt;, 'example': &lt;Example: ответы к 1 самостоятельной&gt;, 'teacher': &lt;SimpleLazyObject: &lt;User: Diana Berkina&gt;&gt;, 'image_work': …

28.03.2024
Always incorrect password in Django

So, the problem is always incorrect password even though its correct. I make sure to type the password correctly in the register and yet in the login its incorrect password. I don't know how to fix it anymore, I'm lost. …

28.03.2024
How to host a react and django application on ec2

I have a React app with Django for the backend and mysql database. I want to host this website on ec2. I have also purchased a domain. currently, I am running the React server and Django server on the ec2 …

28.03.2024
How do I store sensitive user specific data in my Django application?

Users in my Django application all have unique API keys from a third-party service. The feature in my application that I'm building requires the retrieval of the api key with respect to the current user. What are the best practises …

28.03.2024
Cant deploy django-tailwind development server

Ive followed django-tailwind installation docs and did everything until last step, however, when I try to run 'python manage.py tailwind start', I got the following error: `(venv) catatal@catatal-Predator-PH315-52:~/dev/portal_prosesmt$ python manage.py tailwind start &gt; theme@3.8.0 start &gt; npm run dev &gt; …

28.03.2024
Access to stye.css denied - Django Static files - Nginx - I can't make my project read staticfiles (style.css)

I don't know what it could be anymore, I've already given permissions to the files, directories, reviewed the nginx config, the files in sites-available/enabled , I've already cleared the cache through django-shell , I've restarted the instance. I simply don't …

28.03.2024
Writing a Django signal to log user activities in a model

These are my models in the models.py file. class User(AbstractUser): date_of_birth = models.DateField(blank=True, null=True) bio = models.TextField(blank=True, null=True) job = models.CharField(max_length=250, blank=True, null=True) photo = models.ImageField(upload_to='account_images/',blank=True, null=True) phone = models.CharField(max_length=11, blank=True, null=True) followings = models.ManyToManyField('self', through='Contact', related_name='followers', symmetrical=False) def get_absolute_url(self): …

28.03.2024
Django urls works locally, but deployed to heroku all but one work

I am creating a React/Django website for my final project. I have apps, such as posts, profiles, etc., that work perfectly both locally and when deployed to Heroku. However, one of the apps, &quot;base,&quot; works without issue locally but breaks …

28.03.2024
Error creating auth token for newly registered user in Django Rest Framework

I'm working on a Django project where I'm trying to create an auth token for a newly registered user using Django Rest Framework. However, when running the register function, I run into the following error: ValueError: Cannot assign &quot;&lt;User: Test&gt;&quot;: …

28.03.2024
Django site working for all pages except for a few

I'm using a combo of python and django in order to load a site. A HTML home file is also present in the templates folder. I coded all parts of my site the way I normally do, which has worked …

28.03.2024
Аналог set в django tamplate для выводы данных в html-таблицу

Есть таблица ячеек расписания. Каждая ячейка содержит кнопку &quot;Добавить&quot;, если не будет соответствующих дню недели и номеру урока данных из бд, иначе будет кнопка &quot;Изменить&quot;. Я использую обычный template django, из-за чего у меня нет возможности использовать set для установки …

28.03.2024
What is a good throttling rate limit for drf views to secure endpoints

I have two drf class based views endpoints one for login and one for password reset I want to use throttling to prevent bruteforce related attacks to these two endpoints I found a lot of questions discussing the implementation and …

28.03.2024
Fix django login bug

I'm working on a django project, after I finished the code of registration and login feature (serializers and viewsets) I tested theses features, so when the registration feature seems working like a charm, the login feature bug,so when I try …

28.03.2024
How to get an object for editing transfer to a form?

I don't know how to get my announcement to insert into the form for editing my model: class Announcement(models.Model): category = models.CharField(choices=professions, blank=False) title = models.CharField(max_length=40, blank=False) slug = models.SlugField(max_length=250, unique_for_date='publish', ) price = models.IntegerField(default=None, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE, …

28.03.2024
How to handle multiple URL patterns. Any pattern order leads to 404 for different pages

I need your help. There was a problem with the url, the structure is as follows: the main project file urls.py urlpatterns = [ path('admin/', admin.site.urls), path('ckeditor/', include('ckeditor_uploader.urls')), path('', include('shop.urls')), path('', include('informations.urls')), ] shop.urls urlpatterns …

28.03.2024
Python & Django web app - auto emails not sending

I had a web app developed but found the automated emails are not sending. I found the .py file for sending the email, but cannot find another file calling this. filetree showing .py file Is there a …

28.03.2024
How to exclude instances with empty querysets in prefetch_related?

I have two models - Project and Contract. They have one-to-many relationship. class Contract(models.Model): project = models.ForeignKey(Project) I get a qs of Project instances with relevant Contract instance(s). projects = Project.objects.filter(active=True).prefetch_related( Prefetch('contract_set', queryset=Contract.objects.filter(**filters), to_attr='contracts') ) But …

27.03.2024
Django application hosted in vagrant not available at localhost

I have the Vagrant configuration that used to work some time ago, but now the application is not available at localhost after starting in virtual machine. Vagrant file content: # -*- mode: ruby -*- # vi: set ft=ruby : ENV[&quot;LC_ALL&quot;] …

27.03.2024
Как перехватить нажатие кнопки во вьюхе или почему вызывается функция, привязанная к кнопке, при обновлении страницы? (Django)

У меня на сайте надо реализовать публикацию или скрытие поста. Для этого я написал кнопку, которая меняет значение базы данных is_published на 0 или 1 при нажатии, однако значение is_published также меняется при обновлении страницы. Вот views.py: def profile(request): user_now …

27.03.2024
Django formset management_form null value for id_form-TOTAL_FORMS

I have a form with an inlineformset_factory. When the button to add more forms is clicked I receive the error Uncaught TypeError: totalForms is null $addFormset http://localhost:8000/static/js/site-js.js:21 line 21 of site-js.js totalForms.setAttribute('value', '${formsetNum + 1}'); // Increment the Number of …

27.03.2024
How to get data from a form and paste them into template?

I'm trying to make search functionality in my project. There is a form where a person can enter a title of an article and redirect to the page of this article if it exists. But it always gives me &quot;None&quot;. …

27.03.2024
Can't display page content in Django

There is an application posts. There is a model: class Post(models.Model): text = models.TextField() pub_date = models.DateTimeField(&quot;date published&quot;, auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name=&quot;posts&quot;) group = models.ForeignKey(Group, on_delete=models.SET_NULL, related_name=&quot;posts&quot;, blank=True, null=True) def __str__(self): # выводим текст поста return self.text …

27.03.2024
Connecting CSS in Django project

Please tell me what the error is. After running the python manage.py collectstatic files were generated, the js scripts work, but the css file is not connected. base.html &lt;!doctype html&gt; {% load static %} &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; .... &lt;!--Custome CSS--&gt; …

27.03.2024
Python & Django web app how to delete database values without affecting reports

I had a web app developed that is a simple crm used to create estimates, service reports and invoices. It includes a module for tracking inventory. I found if I deleted an item from inventory that the estimates, service reports …

27.03.2024
Payfort - (00073) Invalid request format

I hope everyone is doing well. I'm trying to set up payfort in Django, but I keep encountering this strange error. I believe I'm following all the necessary steps, but whenever I attempt to send a request after tokenization, I …

27.03.2024
Show user location in django admin

There was a task to implement a map in the admin interface in Django. I have a model that stores data about users GPS. class Geoposition(BaseModel): created_by = models.ForeignKey(&quot;User&quot;, on_delete=models.CASCADE, verbose_name=_(&quot;User&quot;)) task = models.ForeignKey(&quot;Task&quot;, on_delete=models.SET_NULL, verbose_name=_(&quot;Task&quot;), null=True, blank=True) longitude = …

27.03.2024
ERROR 403 in Django even after configuring the django-cors-headers package

Is the django-cors-headers exclusive to the DRF? If not, why am I getting an error 403 if I am not using DRF in my project? I already configured the django-cors-header package. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', …

27.03.2024
Missing email key in fields for UserCreationForm in Django

I am having an issue with the UserCreationForm in Django, namely, I receive an error related to the email field, which is my USERNAME_FIELD, not being found in self.fields I subclass the UserCreationForm as such class UserCreationForm(UserCreationForm, CheckUserEmailExtension): &quot;&quot;&quot; A …