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

06.05.2024
Cannot index models from Django to Elasticsearch

I have a Django project where we're going to use Elasticsearch for a full-text search. I have a task to connect it with the existing Django project. The first thing I found django-elasticsearch-dsl package. I did everything like in tutorial …

06.05.2024
Django works perfectly on a local machine, but doesn't work in production

Django works perfectly on a local machine, but has errors with Postgres in production (I am using the same postgres DB in prod and locally). Django server hosted on Railway gives me this:<img src="https://i.sstatic.net/mk31PiDs.png" alt="Railway Deploy Logs" …

05.05.2024
Que aplicaciones desplegar en heroku

El problema es que tengo una aplicacion en python y django que usa conexiones web socket con cnannels y daphne, el asunto es si heroku permite el uso de estas conexiones ya adquiri una suscripcion en pythonAnywhere y me toca …

05.05.2024
ValueError: Found wrong number (0) of constraints for "tours_data"."address"(city_id, street, house_number, entrance_number, floor, flat_number)

Я пытаюсь добавить в unique_together новое поле, но получаю данную ошибку. class Meta: db_table = '&quot;tours_data&quot;.&quot;address&quot;' verbose_name = _('address') verbose_name_plural = _('addresses') unique_together = ( ( 'city', 'street', 'house_number', 'entrance_number', 'floor', 'flat_number', 'point', ), ) Нашел информацию, …

05.05.2024
Automate e2e test with selenium of Django app in gitlab cicd -Error: selenium.common.exceptions.WebDriverException: neterror?e=dnsNotFound

This is the output of my cicd pipline which is failing base/tests/e2e_tests/test_register.py F [100%] =================================== FAILURES =================================== _____________ TestRegistrationPage.test_register_valid_credentials _____________ self = &lt;test_register.TestRegistrationPage testMethod=test_register_valid_credentials&gt; def test_register_valid_credentials(self): &quot;&quot;&quot; Test whether the registration process works flawlessly. This method asserts that after sucessful …

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) но выдает: &quot;TypeError at /polls/user/1/ cannot unpack non-iterable int object&quot;

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 &quot;/usr/local/bin/daphne&quot;, line 8, in &lt;module&gt; sys.exit(CommandLineInterface.entrypoint()) File &quot;/usr/local/lib/python3.8/site-packages/daphne/cli.py&quot;, 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( &quot;User&quot;, null=True, blank=True, on_delete=models.SET_NULL, related_name=&quot;files&quot;, ) 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 &quot;get&quot; but if my function or method starts with &quot;get&quot; 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 &quot;python manage.py runserver 0.0.0.0:8080&quot;, but i got illegal hardware instruction.(history project on my company is using python2.7&amp;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(&quot;hello.urls&quot;)) 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 &quot;player_team() got unexpected keyword arguments: 'player', 'team'&quot; 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(&quot;StudentGroup&quot;, ...) ... class StudentGroup(models.Model): ... class Pair(models.Model): pair_time = models.TimeField(...) pair_date = models.DateField(...) student_group = models.ForeignKey(&quot;StudentGroup&quot;, ...) ... class Mark(models.Model): student = models.ForeignKey(&quot;Student&quot;, ...) …

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(&quot;PmListing&quot;, models.DO_NOTHING) seller = models.ForeignKey(&quot;PmSeller&quot;, models.DO_NOTHING) class Meta: managed = False db_table = &quot;pm_price&quot; this is my serializer: class PmPriceListSerializer(serializers.ModelSerializer): url = serializers.ReadOnlyField(source=&quot;listing.url&quot;) 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: &quot;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 &quot;this field is required&quot;. 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, …