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

05.05.2024
User.username shows incorrect information about the logged in user name

Views.py def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Account has been updated') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': …

05.05.2024
How to import and use Django models inside new process outside views.py, get: Apps aren't loaded yet

I have some models inside 'models.py' inside 'app1' : class ChitaMoney(models.Model): chita_market = models.CharField( verbose_name=_('chita market name'), max_length=20 ) my 'views.py' calls a function from 'multy.py' from 'core' directory inside 'app1' . 'multy.py' startes a new infinite process . …

05.05.2024
Как получит всю информацию о юзере по id в Django?

У меня от юзера есть только его id, как найти остальную инфу? Пытался вот так сделать: user = User.objects.get(id) но выдает: "TypeError at /polls/user/1/ cannot unpack non-iterable int object"

05.05.2024
I'm getting a 503 error when I upload an image to a pre-trained model and try to get output using python + Django on a shared web host

Background: *Beginner here. * I made a simple app with some basic models and trained it to distinguish happy and sad faces. I made this and ran it in a local development server with Django which worked perfectly and I …

05.05.2024
Django uploaded images from admin panel not displayed in the homepage

I created a django project to upload images both from the user interface and from the admin panel. but when uploading images from user interface, the images are not uploaded to the media folder.and also not shown in the homepage. …

05.05.2024
How to read file from DigitalOcean Spaces using Django?

I have a Django app that uses DigitalOcean Spaces to store user-uploaded files. The app then transcribes those files and returns the text. However when I try to read the file using the url to the stored file it fails. …

05.05.2024
Django deploywment with daphne

I want to up my django server with run this command for in daphne: daphne -b 0.0.0.0 -p 9001 core.asgi:application And this error occurred: Traceback (most recent call last): File "/usr/local/bin/daphne", line 8, in <module> sys.exit(CommandLineInterface.entrypoint()) File "/usr/local/lib/python3.8/site-packages/daphne/cli.py", line …

05.05.2024
Django ordering with many to many relationship in model

I am using Django-rest-framework modelviewset, I have a many-to-many relationship with my models below: class Data(TimestampMixin): user = models.ForeignKey( "User", null=True, blank=True, on_delete=models.SET_NULL, related_name="files", ) file = models.FileField(upload_to=user_directory_path, null=True, blank=True) doc_id = models.TextField(null=True, blank=True) url = models.CharField(max_length=255, null=True, blank=True) deleted …

05.05.2024
How do I display an image slideshow using Bootstrap Carousel in Django?

I am trying to display a slideshow using Bootstrap Carousel in Django. The idea is to show multiple images in the slideshow for each event detail (attached with a foreign key). I believe it might have something to do with …

05.05.2024
How can I run tasks in background of djagno project? [duplicate]

I need to run a few tasks in background of my Django project and also I didn't know what is __init__.py file in the Main and App directory in my Django project. I thought myself this file could help me …

05.05.2024
I use decompyle3 or uncompyle6 It decompiles my functions that do not start with "get" but if my function starts with "get" it generates an error?

I use decompyle3 or uncompyle6 It decompiles my functions that do not start with "get" but if my function or method starts with "get" it generates an error: def get_list_patientParse error at or near `POP_BLOCK' instruction at offset 120 so …

05.05.2024
Why uwsgi doesn't disable threads inside django application

Uwsgi docs says, that threads inside an application are turned off until you haven't explicitly turned them on. For me, it works not like that. I have checked it through a simple view in django. uwsgi run …

05.05.2024
How to migrate from Django to drf + nextjs

I divided the Django project into back and front. I saw the reference to drf + next.js, but did not transfer Django to drf + next.js. I made the previously implemented function react. I'm at a loss trying to converting …

05.05.2024
Changes to Django-Parler aren't applied

I'm working on my Django project, and currently I'm incorporating translations and localization, and I have an issue. I used to have the default language as English, but now I want it to be Spanish, but for some reason it's …

05.05.2024
Django-tenants based multi tenant server is not getting accessed from browser

Recently i have configured multi tenancy architecture in Django using django-tenants package. When accessing the newly created tenants on the Django server deployed on development environment( localhost) it is working fine. But on the production environment when i am accessing …

05.05.2024
Is it necessary to use Nuxt Server as an intermediary between my external Django API and the Nuxt 3 frontend in SSR mode?

I am developing a SaaS application using a backend architecture with a Django REST API and a PostgreSQL database, while the frontend uses Nuxt 3 with TypeScript, Tailwind, and TanStack Query for API request management. I have enabled Server-Side Rendering …

05.05.2024
Poetry installed packages not recognized in VS code

I am working on a Django REST API. I use Poetry for the project. First, I made a virtual environment with pyenv, then I ran poetry install to install required packages, such as Django REST Framework, psycopg2 and everything. After …

05.05.2024
HttpOnly cookie in NextJS + Redux + Django API for storing JWT

I'm using NextJS in the frontend, Django API in the backend along with DRF and JWT for authentication and redux for state management. Almost all of my routes requires authentication. I'm able to store and access tokens in http-only cookies …

05.05.2024
Method "PATCH" not allowed error in django

I have django rest framework and with generics views. Whenever I try to make a PATCH request, I get an error that method not allowed. Below is my views.py code class VisitorsLogBooktbViewSet(generics.ListCreateAPIView): queryset = VisitorsLogBooktb.objects.all() serializer_class = VisitorsLogBooktbSerializer class Visitor_data(generics.RetrieveUpdateDestroyAPIView): …

05.05.2024
Django project on macbook pro M1 pro crashed with illegal hardware instruction

environment: 16-inch,2021 cpu: Apple M1 Pro mermory: 16 GB os version: 14.4.1 (23E224) python version: 2.7.15 Heading i try to run "python manage.py runserver 0.0.0.0:8080", but i got illegal hardware instruction.(history project on my company is using python2.7&Django==1.11.29) …

05.05.2024
How to load the sale price based on the selecter with django

Hi I am a beginner on django and I would like to display the sale price depending on the product selected, see my source codes below. I'm stuck and I can't unblock, please I need your help. Thanks for your …

05.05.2024
Whenever I try running the server for django in my virtual enviroment it doesn't work

Whenever I try running the server for django in my virtual enviroment it doesn't work. Example: python manage.py runserver Replies: NameError: name 'include' is not defined I know it's referencing my urls.py where I say path('hello/', include("hello.urls")) but …

05.05.2024
Choosing Between Django and Headless CMS for Website Development: Seeking Advice

I've been delving into the decision-making process for a website project I'm working on for a hotel owner. They're keen on having a robust admin interface to manage various aspects of the site, including a gallery, blog, events, emails, and …

05.05.2024
Custom admin inline for manytomany field

I have a manytomany field called following where all the other users a user is following is stored. I want to be able to view, add, delete the users in this per user in the field. This is my attempt …

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. …