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

06.05.2024
Django, exists subquery always returns False

I faced an issue, that my subquery returns False, even it should return True. from wagtail.models import WorkflowState, Page, Workflow import pytest def test_filter_pages(user): page = PageFactory.create( owner=user, live=False, latest_revision_created_at=timezone.now(), ) WorkflowState.objects.create( content_type=ContentType.objects.get_for_model(Article), base_content_type=ContentType.objects.get_for_model(Page), object_id=str(page.pk), workflow=Workflow.objects.get(name="Moderators approval"), status=WorkflowState.STATUS_IN_PROGRESS, requested_by=user, ) …

06.05.2024
Django stopped updating static files

Django does not upload static files Hey guys, I am head to you because I have a problem I can’t fix. I am on localhost and Django does not apply modifications I have made on static files, although the file …

06.05.2024
Compute number of hours the user spent per day

I have Clocking table in database. I wanted to count the users' time spent per day. For example 2024-03-21, user 1 spend 6.8 hours, the next day he spends n number of hours and so on (['6.8', 'n', ... 'n']) …

06.05.2024
How to restart gunicorn when used with config file

I am using gunicorn to server a django application. I am using a config file and starting gunicorn using the command gunicorn -c config/gunicorn/dev.py I want to know how to restart gunicorn. i am not able to use …

06.05.2024
Python code to connect to FTP /convert my code in way that it uses FTP instead of SFTP [closed]

Please help to write code to connect ftp using python download fresh files from specfic directory load those file in Mysql database ,mark them processed after downloading file from ftp ,after loading them into mysql database If any one can …

06.05.2024
Is it possible to add a "InputField" in ChoiceField in Django? [duplicate]

I'm in the process of developing a form that aligns with a database model. One of the fields in this form requires users to select from a range of options. Initially, I implemented this using Django's ChoiceField. However, I'm exploring …

06.05.2024
Django htmx not targeting assigned element

I have a django-tables2 template that I've modified to assign a unique row id to each row. I'm trying to add a button that will allow a user to delete a given row on a click. I'm using htmx to …

06.05.2024
Django model save operation not creating on default database

I have two databases defined: 'default': { 'ENGINE': 'django.db.backends.postgresql', 'USER': 'app-api-master', 'PASSWORD': 'sdf', 'HOST': 'localhost', 'NAME': 'ev_offshore_bkup' }, 'onshore_db': { 'ENGINE': 'django.db.backends.postgresql', 'USER': 'app-api-master', 'PASSWORD': 'sdf', 'HOST': 'localhost', 'NAME': 'ev_onshore_bkup' } In the model: def save(self, *args, **kwargs): …

06.05.2024
How do we update pip to it's latest version

A new release of pip is available: 23.2.1 -> 24.0 [notice] To update, run: python.exe -m pip install --upgrade pip By running provided command i am unable to update pip to it's latest version. it's showing the following error upon …

06.05.2024
The same uuid is generated for different objects in Django

When I run a server on localhost I am able to add new objects in my postgre database through the Django admin panel, but only one for every table. When I try to add a second new object, it assigns …

06.05.2024
How to implement dual authentication (email and phone number) in Django Rest Framework?

I'm building a Django Rest Framework (DRF) application and I need to implement dual authentication, allowing users to sign in using either their email or mobile number. What is the best approach to implement this? I've already set up the …

06.05.2024
ModuleNotFoundError: No module named 'psycopg2' while makemigrations on postgres DB

I cloned a github project on Django and i was following the instructions to execute the program. I am new so, i went ahead and downloaded postgres and installed it. at the make migrations step, this error was logged along …

06.05.2024
How to Submit Separate Actions from a Single Form Tag? (Django)

I have written the following code where a submit action with the value {{category.name}} unexpectedly triggers the "create" button in form_category, resulting in a "Please enter a name" message. This approach worked fine in a previous project using the same …

06.05.2024
Django Python - How to Query this

I have this Consumer model class ConsumerModel(models.Model): GENDER_LIST = ( ('male','MALE'), ('female','FEMALE'), ("lgbt",'LGBT') ) REGISTER_AS = ( ('consumer','CONSUMER'), ('manager','MANAGER') ) uid = models.CharField(max_length=8) # remove the default value some time profile_id = models.UUIDField() user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name …

06.05.2024
Embedded react component disable select text on other html elements

I am trying to include a react component in a django template which contains non-react content. My template contains the following code: {% load static %} <!DOCTYPE html> <html> <body> <h1>This text CAN NOT be selected</h1> <h2>React app</h2> …

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