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

05.05.2024
Django: unexpected keyword arguements when trying to create new object

I'm trying to create a new object but i keep getting an error message "player_team() got unexpected keyword arguments: 'player', 'team'" I'm just starting out in Django and working on a personal project. I've tried my best to problem solve …

04.05.2024
How do i make a form submission permanent in my django project?

In my django project models.py = from django.contrib.auth.models import AbstractUser from django.db import models from django.utils import timezone class User(AbstractUser): profile_pic = models.ImageField(upload_to='profile_pic/') bio = models.TextField(max_length=160, blank=True, null=True) cover = models.ImageField(upload_to='covers/', blank=True) whatsapp = models.CharField(max_length=25, blank=True, null=True) def __str__(self): return …

04.05.2024
Django prefetch_related nested filter

Got classes of Student, StudentGroup, Pair(double lesson), Mark and a queryset: class Student(models.Model): student_group = models.ForeignKey("StudentGroup", ...) ... class StudentGroup(models.Model): ... class Pair(models.Model): pair_time = models.TimeField(...) pair_date = models.DateField(...) student_group = models.ForeignKey("StudentGroup", ...) ... class Mark(models.Model): student = models.ForeignKey("Student", ...) …

04.05.2024
Django Rest Framework Query issue with filter()

This is my model: class PmPrice(models.Model): created_at = models.DateTimeField() price = models.DecimalField(max_digits=6, decimal_places=2) listing = models.ForeignKey("PmListing", models.DO_NOTHING) seller = models.ForeignKey("PmSeller", models.DO_NOTHING) class Meta: managed = False db_table = "pm_price" this is my serializer: class PmPriceListSerializer(serializers.ModelSerializer): url = serializers.ReadOnlyField(source="listing.url") shop …

04.05.2024
While mutating shares of a Post, I get "Variable '$postId' got invalid value {'isTrusted': True, '_vts': 1714830156331} ID cannot represent value

Using Vue 3 and Django backend using Graphql, I want to count button click shares.The problem is referring to PostId of Post model in django and graphene-django gives me error: "Variable '$postId' got invalid value {'isTrusted': True, '_vts': 1714830156331} ID …

04.05.2024
LoginRequiredMixin not work Properly with login URL

I'm working on a Django project where I have implemented a ListView to display a list of checkout items (ListCheckoutView). I want to require authentication for accessing this view, but currently, it's accessible even without logging in. I've tried using …

04.05.2024
Django Form - POST method not recognised as POST in views

In my django project, I am trying to create a form which the user will access through a specific url. By clicking on the url, the user will be automatically redirected to a pager_id. Inbetween the user click on said …

04.05.2024
Django gives me a bad request error 400 when I want to fill a table

When I want to fill in the MRZ table it gives me the bad request error knowing that all the attributes are retrieved from my flutter mobile app except for the ccp_account which gives me nothing when I want to …

04.05.2024
Generate PDF with picture Django rest framework

With the code below, I can easily generate a PDF: import weasyprint def admin_order_pdf(request, sell_id): # working fine try: sell = Sell.objects.get(id=sell_id) except Sell.DoesNotExist: return HttpResponse('Sell object does not exist') html = render_to_string('sell_invoice.html', {'sell': sell}) response = HttpResponse(content_type='application/pdf') app_static_dir = …

04.05.2024
Setting DateTimeRangeField programmatically via a ModelForm

I'm trying to set the DateTimeRangeField in a Django ModelForm form, but I'm getting a validation error "this field is required". It seems that Django is not recognizing nor psycopg2.extras.DateTimeTZRange instance, nor any date strings as a valid value. How …

04.05.2024
How to manage language redirection in Django middleware with user authentication?

I am developing a middleware in Django to manage language redirection based on the user's language preference, which can be stored in the database or specified in a cookie. The middleware needs to handle URLs that include a language prefix, …

04.05.2024
Calling the create method of a ModelViewSet from another ModelViewSet

I need to create objects of model B from the views.py file of A. I was able to do it using the serialiser of B (see # OLD METHOD using serializer) but I would like to know how to use …

04.05.2024
JSONDecodeError : Extra data: line 1 column 5 (char4) when using an API & JSON in Django

When i use the SVD Stability.api API there is an error shown to me which is like this in Django, the API i used is this https://platform.stability.ai/docs/api-reference#tag/Image-to-Video …

04.05.2024
Django 4.2.11 is not supported with SQL Server

I am using Django 4.2.11 and connected to django-pyodbc-azure Version: 2.1.0.0. The code was running fine but now I start getting an error and can't run it. Did anyone knows how to solve this problem? Error: /Users/zinabadnan/Library/Python/3.9/lib/python/site-packages (from asgiref<4,>=3.6.0->django) (4.9.0) …

04.05.2024
Ways to providing data to your frontend

As I progress with the backend development of this website ( with django and DRF but i don't think it matters in this question), I've come across a question regarding the organization of API endpoints, particularly with regards to providing …

04.05.2024
My images uploaded from ckeditor5 in django to cloudflare r2 stop working

So the images initially upload and are appear in my posts but eventually the link stops working after an hour or so. Has anyone had this issue before? It looks like they are going into the rootfolder in my mediabucket. …

04.05.2024
Trying to utilize Supabase S3 Storage with Django

If USE_S3: # aws settings AWS_ACCESS_KEY_ID = os.getenv("SUPA_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.getenv("SUPA_SECRET_KEY") AWS_STORAGE_BUCKET_NAME = "images" AWS_S3_REGION_NAME = os.getenv("SUPA_S3_REGION_NAME") AWS_ENDPOINT_URL = os.getenv("SUPA_S3_DOMAIN") # s3 static settings STATIC_LOCATION = "static" STATICFILES_STORAGE = "storages.backends.s3boto.S3BotoStorage" # s3 public media settings DEFAULT_FILE_STORAGE = "storages.backends.s3boto.S3BotoStorage" else: STATIC_URL …

04.05.2024
Field Validator not getting called in Model Serializer

I am quite new to Django. I am working on a django app which needs to store films, and when I try to load film instances with the following program: import os import json import requests # Assuming …

04.05.2024
Как правильно работать с группами и разрешениями?

Для своего проекта хотел создать группу Модераторов, которые могут изменять и удалять записи. Модель для группы такая: class Group(models.Model): name = models.CharField(max_length=150) permissions = models.ManyToManyField(Permission, verbose_name='Права', blank=True, related_name='perms') Во вьюшке прописал такой код: def create_moderator_group(): group, _ = Group.objects.get_or_create(name='Moderators') …

03.05.2024
How to properly set up React proxying on a Chromebook?

I am running a Django backend app on port 8000 and would like to configure a React app proxy calling that particular Django backend app. I have added "proxy": "http://localhost:8000", to package.json and used shorthand url notations (such as …

03.05.2024
Axios Error and errors with postrgresql on django deployment

Simple django/react app just start learning how to deploy with railway. current error is "Unsupported protocol postgresql:" so tried adding "http://" and "https://" to the api url, which gave cors error and still wasn't working, so reverted back to code …

03.05.2024
Docker контейнер для django приложения, при отправке сообщения на почту, выдает ошибку ssl.SSLCertVerificationError, как ее устранить?

Я работаю с django приложением, которое я поднимаю через команду: docker compose up --build. Контейнер собирается исправно, но когда дело доходит до отправки сообщения на почту все падает со следующим текстом ошибки email_sender | Traceback (most recent call last): …

03.05.2024
Many to many serializers error in post api

I have many-to-many relationship between Movie and Person through Cast. I use CastSerializer to create post method to create new movie and new cast relationship, but when call post method, response return AttributeError. I want my post body like this: …

03.05.2024
Complex constraint in a Django model

I have a use case where I want to validate that a field ForeignKey value is in a particular set, so something like: class Role(models.Model): label = models.CharField(max_length=24) class Group(models.Model): roles = models.ManyToManyField(Role, null=False) class Member(models.Model): label = models.CharField(max_length=24) group …

03.05.2024
403 forbidden error in Django admin even though superuser was already created

Recently, i cloned a project from github to get more familiar with projects written in Django. Previously, everything was running fine, but today when i tried to sign into the Django admin page it gave me this error: 403 Forbidden …

03.05.2024
My form doesn't return any errors in Django

I am a Django developer, and I am trying to put two forms in one HTML file(register and login forms), but when I write an invalid input into them, they don't return any errors. views.py: def log(request): if request.method == …

03.05.2024
Как из существующей модели сделать базового пользователя

В models.py прописана бд с сущностью Account, как из этой сущности сделать базового пользователя для входа в аккаунт. class Account(models.Model): email = models.EmailField() FML = models.TextField() login = models.TextField() phone = models.IntegerField() def __str__(self): return self.login Так же на …

03.05.2024
How to inject something at the end of every render in Django?

I want to inject a specific HTML comment at the end of every render of HTML in Django. I don't want to write that at the end of base.html template, but want it to be injected by code. Is there …

03.05.2024
Django. Программа при запуске через manage.py не использует виртуальное окружение

Пишу бота для телеграмма и использованием Django. Бот запускается через файл tg_bot/management/commands/bot.py. При запуске команды через manage.py скрипт не видит виртуальную среду и выводит сообщение, что модуль не найден. `Traceback (most recent call last): File "C:\Users\ivan\Documents\vs_code\eleshop\tg_bot_shop\tg_bot\bot.py", line 1, in <module> …

03.05.2024
Django & dependency injection

In the past, I've used dependency-injector, but it looks like it's unmaintained now. :-( Does anyone have any good suggestions for a DI package? I'd want to be able to inject dependencies into views, …

03.05.2024
Not able to add Images and videos using quill rich text editor from local machine

Not able to Add Images and videos using Quill.js rich text editor. I have added quill editor in my django blog site,everything works fine but when i try to click image icon to add the image's from local machine i …

03.05.2024
Crispy tag leads to Hidden Field TOTAL_FORMS is a required field. error on POST

I have the following form in my template: <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {% crispy blog_form %} {% for form in formset %} {% crispy form %} {% endfor %} <button type="submit">Save</button> </form> However: …

03.05.2024
How to set manifest_storage for ManifestFilesMixin (Django)

I use django-storages to serve my static files from S3. I want to use the ManifestFilesMixin for cache busting my CSS and JS files. The following works fine: from django.contrib.staticfiles.storage import ManifestFilesMixin from storages.backends.s3boto3 import S3Boto3Storage class ManifestS3Storage(ManifestFilesMixin, S3Boto3Storage): pass …

03.05.2024
Django-translations not returning models translations on DRF

I have a project setup with django 3.2.5 and drf 3.14.0 on python 3.6 and postgres 9.6. I followed the following steps to create a translatable model for learning products model. using this library for translations here. …

03.05.2024
JS result of year-link click lands in the false column

I have a 2-columns (div) page. Left column: the posts right column: the respective years The years are clickable: if a year is clicked the result should filter the posts in the left column. The error: after a year-click, the …

03.05.2024
Can't apply static file in django / docker

Enter image description here what I have to next ? give me some advice .. it's github repository https://github.com/OZ-Coding-School/oz_02_collabo-006-BE/tree/Feature-docker i want to apply css and solve cors error nginx.conf server { listen 80; …

03.05.2024
Railway Error when deploying DJango App due to botocore dependency (boto3)

After installing boto3 package to integrate with AWS S3 buckets, the application fails on deployment. The Railway error is "botocore 1.34.93 depends on urllib3<1.27 and >=1.25.4; python_version < "3.10". On the local server (127.0.0.1:8000) everything works fine, and app deployed …

03.05.2024
I get this error when sending a POST request: MissingSchema: Invalid URL 'None/orders': No scheme supplied. Perhaps you meant https://None/orders?

I'm getting this error when I use Insomnia to send a POST request to an API of my backend code (which is running on my desktop) when I try to create an order. But when I send the same request …

03.05.2024
I tried uploading a python app using Django into a live server and got null return errors

I am learning some Django along with python and created a project recently. The project worked as i wanted in the development local server but when i uploaded it to a live server on the web I got so many …

03.05.2024
Django Signals : Access ManyToManyRel value from instance

I have the following signal : @receiver(post_save, sender=Document) def handle_added_or_edited_element(sender, instance, **kwargs): ''' This signal is used to compare the original and the current instance of the object being saved. If at least one field has changed, a row is …