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

21.11.2024
Unable to save user model with new data

Django 4.2.5, python 3.11, saving to mysql db. I am trying to update the "chat_user_status" field for my "Teacher" model, which extends the abstract User model. Model.py code for Teacher: class TeacherProfile(models.Model): teacher = models.OneToOneField( UserProfile, related_name='teacher', primary_key=True, parent_link=True, on_delete=models.CASCADE) …

21.11.2024
Django 2 DB columns as FK to the same related table

I have a table 'Athletes' and another table 'Parents'. Table fields are: ATHLETES reg_number first_name last_name gender age_group (as FK to AgeGroup) parent_1 (as FK to Parents using related_name='parent_1') parent_2 (as FK to Parents using related_name='parent_2') PARENTS …

21.11.2024
Difference between Apple Sign-In Token Request: /auth/token vs /auth/keys

I am working on a Flutter + Django REST Framework application and implementing Apple Sign-In functionality. When Iam tried to manually obtain the user's access_token, I followed the flow where needed to generate a client_secret on the backend (it was …

20.11.2024
Count distinct on an aggregated dimension

I have the following model: class Historique(models.Model): type_of_object_choices = ( (1, 'Cadeau') , (2, 'Offre') , (3, 'Commentaire') ) event_type_choices = ( (1, 'modification') , (2, 'creation') , (4, 'suppression') ) wishlist = models.ForeignKey(Wishlist, on_delete=models.CASCADE) type_of_object = models.IntegerField(choices=type_of_object_choices, null=True) event_type …

20.11.2024
Gunicorn on Apache Server not serving static files in Django project: "Not Found" error for /static/

I’m running a Django project using Gunicorn and Apache with mod_wsgi, but Gunicorn is not serving the static files correctly. When I try to load my page, I get errors like: Not Found: /static/css/style.css Not Found: /static/js/app.js In browser console …

20.11.2024
Django - Failed Login Redirecting To Different Page

I am new to Django and I am trying to use the authentication system. I have managed to get it working using the default Auth URLS. (/accounts/login) etc. I want to get a login form on my homepage so it …

20.11.2024
Django QuerySet performance

I'm debugging sitemap generation, and finally have the following snippet: items=Event.objects.all() for limit in (1000, 10000, 20000): events=items[:limit] print(f'{limit=}') start=time() for obj in events.values('id', 'slug', 'date_updated'): s='/events/{0[slug]}_{0[id]}_{0[date_updated]}/'.format(obj) print(f' Time spent: {time()-start:.2f}') start=time() for obj in events.only('slug', 'date_updated'): s=f'/events/{obj.slug}_{obj.pk}_{obj.date_updated}/' print(f' …

20.11.2024
Get currenty logged in user in Django/Angular

I am creating a Django / Angular project but I am having an issue. In normal django applications without frontend framework we can just do request.user and we can get the iformation needed. I already created the api endpoints to …

20.11.2024
Django HTTPS with nginx as reverse proxy. Issues with CSRF tokens

I developed a Django application which runs inside a docker container. Outside the container, a natively running nginx does the reverse proxy-ing of the requests to that django application. Django runs via WSGI with gunicorn. General setup: I use …

20.11.2024
Django: how to "expand" a field which references an enum but not another table

I have a main table "PfPersona" with a field "stato_civile" that takes 1 char (the "key" of an enum). For this example let's say the enum has only one value. In DB the value would be "S". Is the definition …

20.11.2024
How to resolve Third-Party Login Failure

I am having trouble using Github as third party for logging in to an app. I am getting this error (page): Third-Party Login Failure An error occurred while attempting to login via your third-party account. My alluth version: django-allauth==65.2.0 …

20.11.2024
Deployed Krakend Django microservice not receiving any input data given in json body

I have a Django application deployed with Krakend gateway. All endpoints are active. But the service is unable to access the request data. I'm giving the request as below curl --location 'https://backend-dev-url.com/api' \ --header 'Content-Type: application/json' \ --data '{ "a":"value", …

20.11.2024
Template Syntax Error when using Django allauth

I encountered this error when trying to improve the UI of login and signup pages.. TemplateSyntaxError at /accounts/logout/ 'slippers' is not a registered tag library. Must be one of: account admin_list admin_modify admin_urls allauth allauth_ui cache i18n l10n log socialaccount …

20.11.2024
Sort and search functionality not working together

I have the following search and sort functions in my javascript file and the following html file Javascript file document.addEventListener('DOMContentLoaded', function() { const csrfToken = document.getElementsByName('csrfmiddlewaretoken')[0]?.value; const resultsListFW = document.getElementById('list-results-fw'); const listFW = document.getElementById('list-fw'); const searchInputFW = document.getElementById('search-input-fw'); function renderFWData(data) …

20.11.2024
Django How to update the session cart icon after admin delete a product

I have two apps in my project one is call store and the other is call cart in store I have all the models and in cart I have all the cart functionality. The call is handle using session when …

19.11.2024
Error: connect ECONNREFUSED ::1:8000 in Nuxt 3

I’m working on a Nuxt 3 project and encountering the following error: [nitro] [unhandledRejection] connect ECONNREFUSED ::1:8000 This error occurs when I try to make API requests to my backend during development. I suspect it’s related to the frontend …

19.11.2024
Cuncurrency, mutex, semaphores on django and a cron job

I want to create a critical section in django provide controlled section. One of this is in one of the django channels consumers handling the websocket connections and the other is in a cron process implemented with cron tab, not …

19.11.2024
Coverage: How to gracefully stop a Django development server that runs on a Github Action Instance

I am testing some API endpoints of my Django app by running Playwright separately on a Ubuntu machine on my Github Action instance. Since I also want to get the coverage of the tests, I am starting my server this …

19.11.2024
TemplateSyntaxError at / Could not parse the remainder: '(item.star)' from 'range(item.star)'

This my code I wanna added star on my shop {% with '' |center:item.star as range %} {% for _ in range %} <div class="bi-star-fill"></div> {% endfor %} {% endwith %} And django error says TemplateSyntaxError at / Could …

19.11.2024
How do I update a Django field in an HTML template

I have a Django app that among other things wants the user to enter a date of birth or their age. Upon the entry of one, the other should be calculated and when the form is saved, the database should …

19.11.2024
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYT

As i made to apps accounts and core . in accounts model i have created custom user and in core i made userpreference model i want to import accounts.models customuser but it gives error above mention i have tried the …

19.11.2024
What strategies can I use to handle occasionally long running blocking database tasks in Django

I have a scientific data submission validation interface on my website. It essentially does a dry run load of the data and reports whether the dry run load succeeds and if it does not, it gives a report on errors …

19.11.2024
Django-tables2: hyperlink in cells

I have a view named events displaying two columns. One eventType and a second eventDates, listing dates. It looks like this: eventType eventDate foo 1900-01-01, 2010-02-02 bar 2000-01-01, 2010-02-02, …

19.11.2024
Making an AI security app using django and react-native, but the output that is sent by django does not show on android and ios but does show on Web

Making a security app that will using a classification model detect who is at my door (members of my family for now) and show it on an App that i am making in react-native. Ive got most of the code …

19.11.2024
No domain link when ı launched my website on aws elasticbeanstalk

ı get some errors on aws elastic beanstalk and ı can not get domain link, my website contains data but ı didnt use database when ı do configurations …

19.11.2024
State is lost following Apple login via python social auth (AuthStateMissing)

I've added apple-id to a django project that already has facebook & twitter login implemented & working. From the application you can get to apple, login and then you come back to the /player/social/complete/{backend}/ path. Here there's an AuthStateMissing: Session …

19.11.2024
Apple signin/login with django and flutter problem - invalid_client response

I'm having an issue with implementing Apple Sign-In/Login in my Django + Flutter application. Here's the flow I'm using: On the Flutter side, I'm using the following code to get credentials from Apple: SignInWithAppleButton( onPressed: () async { …

19.11.2024
Get_absolute_url django admin session id missing

I'm using Django's "View on site" feature to navigate from the Django admin to a specific page in my application for a model instance. On this page, a GET request is made to retrieve data using a Django ModelViewSet. The …

19.11.2024
Django docker poetry mysql driver problem [closed]

I'vse used django a milion times and docker half a million times but this time i can't get it to work Image: FROM python:3.11.5-slim-bookworm AS python-base Dockerfile: apt-get install --no-install-recommends -y python3-dev default-libmysqlclient-dev build-essential pkg-config Poetry …

19.11.2024
How to create a Django Admin link with preselected objects and a pre-filled action?

I am trying to generate a link that takes users to the Django Admin page for a specific model, with certain objects already selected and an action pre-filled in the dropdown menu. Here’s what I’ve tried so far: def get_admin_action_link(record, …

19.11.2024
How to Run Functions in Parallel or in the Background in Django Without Using Celery/Redis?

I have a use case in my Django application where I want to run two functions in parallel or execute a process in the background. I don't want to use third-party tools like Celery, Redis, or similar services for this. …

19.11.2024
Django API with Redis Cache Not Updating Immediately After POST/PUT/DELETE Requests

I'm developing a Django REST API using Django, Redis, and SQLite. The goal is to cache data for GET requests to improve performance, using Redis as the caching layer. Issue: When I create, update, or delete Category or Product …

19.11.2024
Caching daily data in Django, and caching more on request

I'm currently building a website where I each day want yesterday's financial data cached for the full day, to be quickly available to users. I also want to cache older data on request, e.g. if a user looks at data …

19.11.2024
Django сигналы, как подключить к проекту?

Планирую дописать некоторый функционал для портала. Идея заключается в том, что при создании сущности одной модели, автоматически создавались сущности другой модели при сохранении. В настоящее время это реализовано через кастомный метод create(), который при создании модели проверяет наличие нужных сущностей …

19.11.2024
Django all-auth extended SignupForm is valid but save method is not called

I am using Django all-auth in conjunction with django. I am also extending their default signup form. The form renders correctly, fields are validated correctly, the form returns as valid if checked but the save method isn't even called. These …

19.11.2024
WebSocket Connection Failure and Unexpected Socket Closure in Django Channels

I'm experiencing issues with establishing and maintaining a WebSocket connection in my Django project using Django Channels. I've set up a notification system that uses WebSockets to broadcast messages to connected clients. However, I'm encountering two errors: "WebSocket connection …

18.11.2024
Inline Serializer for Request Body Not Displaying in DRF Spectacular Documentation

I am working on a Django REST Framework (DRF) project using DRF Spectacular for API documentation. My ViewSet does not use a serializer because the logic does not require one, but I need to describe the request body shape in …

18.11.2024
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc2 in position 61: invalid continuation byte [closed]

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc2 in position 61: invalid continuation byte help me solve the problem, I want to migrate a database in a project in Django from sqlite to postgres and when I use the python manage.py …

18.11.2024
Django unit test with parallel db accesses giving database locked error

I am writing some Django unit tests to validate the behavior of my application when multiple clients access it at the same time. I have done this by writing tests like this: from django.test import TestCase from django.db import connection …

18.11.2024
Не работает аутентификация на хостинге DRF JWT

Сделал бэк проекта на Django rest, все протестировал, все работает хорошо, решил его залить на хостинг, все работает кроме аутентификации, как бы я не пытался передать токен всегда получаю: { "detail": "Учетные данные не были предоставлены." } вот я получаю …