Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker error: failed to solve: process "/bin/sh -c pip install -r requirements.txt" did not complete successfully: exit code: 2
I've recently cloned my repository to a new device. My repository is run in a docker environment. However, despite having one successful docker image build on this device, whenever I try to build a new Docker image(by running docker build . ) I encounter this error when installing in requirements.txt: Dockerfile:30 -------------------- 28 | # Install dependencies 29 | COPY requirements.txt . 30 | >>> RUN pip install -r requirements.txt 31 | 32 | # Copy project -------------------- ERROR: failed to solve: process "/bin/sh -c pip install -r requirements.txt" did not complete successfully: exit code: 2 I haven't been able to find anything related to error code 2 online. I've restarted Docker and ran the command at least 10 times. I've also increased pip timeout to 2 mins using set PIP_TIMEOUT=120 but it still results in the same error. Here is the full traceback(along with the last package being installed: Collecting nvidia-cudnn-cu11==8.5.0.96 (from torch==2.0.1->-r requirements.txt (line 45)) 179.9 Downloading nvidia_cudnn_cu11-8.5.0.96-2-py3-none-manylinux1_x86_64.whl (557.1 MB) 239.0 ━━━━━━━━━━━━━━━━━╸ 250.1/557.1 MB 1.1 MB/s eta 0:04:38 239.0 ERROR: Exception: 239.0 Traceback (most recent call last): 239.0 File "/usr/local/lib/python3.11/site-packages/pip/_vendor/urllib3/response.py", line 438, in _error_catcher 239.0 yield 239.0 File "/usr/local/lib/python3.11/site-packages/pip/_vendor/urllib3/response.py", line 561, in read 239.0 data = self._fp_read(amt) if … -
EOF error occured in Docker compose up (Django)
I have EOF error when python manage.py makemigrations in docker compose up (0.001) SELECT "django_migrations"."id", "django_migrations"."app", "django_migrations"."name", "django_migrations"."applied" FROM "django_migrations"; args=(); alias=default Traceback (most recent call last): File "/code/manage.py", line 22, in <module> main() File "/code/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 106, in wrapper res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py", line 235, in handle changes = autodetector.changes( File "/usr/local/lib/python3.10/site-packages/django/db/migrations/autodetector.py", line 46, in changes changes = self._detect_changes(convert_apps, graph) File "/usr/local/lib/python3.10/site-packages/django/db/migrations/autodetector.py", line 179, in _detect_changes self.create_renamed_fields() File "/usr/local/lib/python3.10/site-packages/django/db/migrations/autodetector.py", line 955, in create_renamed_fields if self.questioner.ask_rename( File "/usr/local/lib/python3.10/site-packages/django/db/migrations/questioner.py", line 220, in ask_rename return self._boolean_input( File "/usr/local/lib/python3.10/site-packages/django/db/migrations/questioner.py", line 101, in _boolean_input result = input() EOFError: EOF when reading a line This is my Dockerfile FROM python:3.10.11 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ RUN chmod +x /code/entrypoint.sh ENTRYPOINT ["sh", "-c", "/code/entrypoint.sh"] And it is my docker-compose.yml version: '3.8' services: db: image: postgres:14.10-alpine volumes: - postgres_data:/var/lib/postgresql/data environment: - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} - POSTGRES_DB=${DB_NAME} django: build: . … -
how to redirect "back" button in browser using Django
I am developing a testing system for students using django, the idea is that if a student wants to pass a test, he must enter an access code that the teacher will send him. I faced the problem that when the student finished the test and clicked the send answers button and was transferred to the results page, he can return to the test by clicking the "back" button in the browser. I need that if he clicked this button on the results page, he would be transferred to the main page here is my code: def test(request): unique_code = request.POST.get('accessCode',None) first_name = request.POST.get('first_name',None) last_name = request.POST.get('last_name',None) if unique_code: try: # We get the model with a unique key TestFile = Test.objects.get(unique_code=unique_code) if not os.path.exists(TestFile.file.path): return HttpResponse('File not found') except Test.DoesNotExist: return HttpResponse('File not found') questions = [] answers = [] isQuestion = False with open(TestFile.file.path, "r", encoding="utf-8") as f: for line in f: # Checks if the string is not empty if line != '\n': if not isQuestion: questions.append(line.strip()) isQuestion = True else: tempAnswers = [] tempVal = line.strip() tempAnswers.append(tempVal) for temp_line in f: if temp_line == '\n': break tempAnswers.append(temp_line.strip()) answers.append(tempAnswers) isQuestion = False # We save the data … -
Custom manager isn't accessible via model instances
This is my model: class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status=News.Status.PUBLISHED) class News(models.Model): class Status(models.TextChoices): DRAFT = 'DF', 'پیشنویس' PUBLISHED = 'PB', 'منتشر شده' user = settings.AUTH_USER_MODEL image = FileBrowseField( 'تصویر خبر', max_length=255, directory='news/', extensions=['.png', '.jpg'] ) title = models.TextField('عنوان خبر') slug = models.SlugField( 'نامک', max_length=255, unique=True, help_text=('نامک آدرس لینک خبر در مرورگر است و باید یکتا باشد.'), allow_unicode=True, ) author = models.ForeignKey( user, on_delete=models.CASCADE, related_name='news', verbose_name='نویسنده' ) body = RichTextUploadingField('متن خبر', config_name='extended') publish = models.DateTimeField('تاریخ انتشار', default=timezone.now) created = models.DateTimeField('تاریخ ایجاد', auto_now_add=True) updated = models.DateTimeField('بروزرسانی', auto_now=True) status = models.CharField( max_length=2, choices=Status.choices, default=Status.DRAFT ) objects = models.Manager() published = PublishedManager() class Meta: ordering = ['-publish'] indexes = [models.Index(fields=['-publish'])] verbose_name = 'اخبار' verbose_name_plural = 'اخبار' def __str__(self): return self.title But I get "AttributeError: Manager isn't accessible via News instances. Did you mean: 'publish'?" I've read other posts about this problem. None of them are applicable here? The above code is actually from a book called Django 4 by Example with slight modifications. -
Django formset is valid but returns empty dict list
I'm attempting to render a form that is a table where each row contains a name and a checkbox to allow the user to select players for a game. Googling around I've realized that I need to generate a formset so that each line in the table is a separate form. I finally have the table rendering correctly and posting without errors but what I've found is that while the formset is valid, the cleaned data contains a list of empty dicts. I found some StackOverflow posts that were similiar that said to create your own Formset class and set empty_permitted=True but that did not fix my issue. I can't seem to get passed this issue so any help is appreciated. Code Snippets # forms.py class InvitePlayerForm(forms.Form): """ Form to invite players to the new game """ invited = forms.CheckboxInput() class InvitePlayerFormset(BaseFormSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for form in self.forms: form.empty_permitted = False # views.py ef create_game_players(request): """ View to invite players to a game """ context = dict() # if this is a POST request we need to process the form data if request.method == "POST": num_players = request.session["invites"]["num_players"] print(f"num_players: {num_players}") invite_formset = formset_factory(InvitePlayerForm, formset=InvitePlayerFormset, extra=num_players) invite_forms … -
How to use django orm in python-socketio inside django project?
Now I created new app "ws" (it's in INSTALLED_APPS) and I use this code there in views.py: import socketio #from task_tracker.models import TaskColumn sio = socketio.Server(cors_allowed_origins="*") app = socketio.WSGIApp(sio) @sio.event def connect(sid, environ): print(sid, 'connected') @sio.event def disconnect(sid): print(sid, 'disconnected') @sio.event def getColumns(sid, environ): print(environ) I run this code with: gunicorn -b 127.0.0.1:5000 --threads 50 views:app And everything is fine till I try to import my model from the other app. The error is: (venv) dbte5@Denis-MBP ws % gunicorn -b 127.0.0.1:5000 --threads 50 views:app [2024-04-05 18:00:52 +0500] [3112] [INFO] Starting gunicorn 21.2.0 [2024-04-05 18:00:52 +0500] [3112] [INFO] Listening at: http://127.0.0.1:5000 (3112) [2024-04-05 18:00:52 +0500] [3112] [INFO] Using worker: gthread [2024-04-05 18:00:52 +0500] [3113] [INFO] Booting worker with pid: 3113 [2024-04-05 18:00:52 +0500] [3113] [ERROR] Exception in worker process Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/gunicorn/arbiter.py", line 609, in spawn_worker worker.init_process() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/gunicorn/workers/gthread.py", line 95, in init_process super().init_process() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() ^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() ^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() ^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/gunicorn/util.py", line 371, in import_app mod = … -
TemplateDoesNotExist using django_tables2
I'm developing a Python Django application and I've come across this error: when the view passes a table, I get a "TemplateDoesNotExist" error, but when passing a query, the template works. I've installed 'django_tables2' and added everything to the installed_apps in the settings.py file. The file log_allarmi.html extends componenti/list.html, which in turn extends base.html. Installed Apps - settings.py Template DIR - settings.py View log_allarmi Templates tree I have verified that everything was installed correctly, but I might have overlooked something. Thank you for the help. -
nginx no carga css, js, etc
Tuve el siguiente problema, tengo un sistema alojado en un droplet de digital ocean, soy nueva en este servidor asi que cualquier ayuda me sirve. El mismo funcionaba sin problema hasta que venció el dominio y dejo de cargar. Por cuestion de tiempo, el mismo debio volver a ser registrado y delegado ya que no alcance a renovar. Antes de ser registrado nuevamente se ingresaba mediante la ip publica y cargaba sin problema, por ejemplo http://125.31.190.131/home/ pero luego de hacer el proceso mencionado del dominio el acceso al sistema se empezó a cargar mediante el puerto 8001, es decir http://125.31.190.131:8001/home/ ya que si ingresaba como al principio solo levantaba apache y no el sistema en si. Por si sirve el sistema carga mediante gunicorn django/python y mediante nginx los archivos static El problema especifico seria nginx que dejo de responder ya que al ingresar al sistema no reconoce las rutas de los static. Me fije en los archivos log de error y no se encontraron, incluso las rutas de configuración donde se encuentran los static, tambien en la configuracion nginx se encuentra configurado "listen 80" y por las dudas quise cambiar a 8001 pero nginx deja de funcionar. -
Django deploy on Heroku causes causes too many connections error
I have a well-established Django app running on Heroku. It has a Heroku Postgres Standard 0 plan. My latest build upgraded the app to Python 3.12 and Django 4.0, as well as a few dependencies, specifically: redis>=4.0.0 APScheduler==3.10.4 mozilla-django-oidc==4.0.1 channels-redis==4.2.0 channels==4.0.0 daphne>=4.0.0 In addition, the channels upgrade broke part of my app which uses channels and I couldn't get the SSL None to work so I amended CHANNEL_LAYERS to: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { 'hosts': [f"{REDIS_URL}?ssl_cert_reqs=none"] }, }, } Other than the above, there were no changes to any source code. I tested everything locally and again on my test Heroku Staging server and all was fine. When I deployed to my Heroku Production server my site ground to a halt with the following error: app/heroku-postgres source=HEROKU_POSTGRESQL_DB addon=postgresql-db sample#num_connections_over_limit=90 message=Database connections over limit. Please upgrade your database plan. In the end my only solution was to roll back to the previously deplyed version. I inspected the number of connections to the Postgres DB and found: In the original working deploy the number of connections would typically sit anywhere between 20 and 24 As soon as this new version was deployed the number of connections rocketed to … -
How to add an explicit field in UserSerializer?
The following error is being shown with the new release of python 3 in django and I can figure out how to get the URL running. from django.contrib import admin from django.urls import path, include from api.views import CreateUserView from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView urlpatterns = [ path('admin/', admin.site.urls), path("api/user/register/", CreateUserView.as_view(), name="register"), path("api/token/", TokenObtainPairView.as_view(), name="get_token"), path("api/token/refresh", TokenRefreshView.as_view(), name="refresh"), path("api-auth/", include("rest_framework.urls")), ] urls.py from django.shortcuts import render from django.contrib.auth.models import User from rest_framework import generics from .serializers import UserSerializer from rest_framework.permissions import IsAuthenticated, AllowAny # Create your views here. class CreateUserView(generics.CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [AllowAny] views.py from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User field = ["id", "username", "password"] extra_kwargs = {"password": {"write_only": True}} def create(self, validated_data): user = User.objects.create_user(**validated_data) return user serializers.py -
Real time data not display it return an error message: {"error": "'QuerySet' object has no attribute 'body'"}
I like to implement real time data display in django app using Ajax, i want to enable user to be able to see what they are writing in real time, to do this, i'm using django JsonResponse, using the below method: def get_real_time_data(request): if request.method == 'POST': body = request.POST.get('body') try: question = Question.objects.filter(body=body) if question is not None: content = question.body response_data = { 'content': content } return JsonResponse(response_data) else: return JsonResponse({'error': 'No content found for the given body'}, status=404) except Exception as e: return JsonResponse({'error': str(e)}, status=500) else: return JsonResponse({'error': 'Invalid request method'}, status=400) Using the above method, it's means, every time, a user started writing something in the form, the data will be displayed in real time, but I don't know why the data does not display, instead, it return an error message in the browser console: Failed to load resource: the server responded with a status of 500 (Internal Server Error) question/:89 {"error": "'QuerySet' object has no attribute 'body'"} error @ question/:89 :8000/get-real-time-data/:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error) question/:89 {"error": "'QuerySet' object has no attribute 'body'"} error @ question/:89 jquery.min.js:2 POST http://127.0.0.1:8000/get-real-time-data/ 500 (Internal Server Error) … -
I am getting a console.log error in my django react application with CORS_ALLOWED_ORIGINS
According to the docs I have everything set up correctly but I am still getting an error. This is the error message from console.log() Access to fetch at 'http://127.0.0.1:8000/api/wells' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. This is the code from settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'wells', 'core', ] CORS_ALLOWED_ORIGINS = ['http://localhost:3000'] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] According to the docs, this should work. So, I am not sure how to fix the error. -
SQLALCHEMY cursor and execute AttributeError
I'm currently using sqlalchemy 2.0.29 in django with postgres sql and while updating an entry i encountered AttributeError regarding cursor and execute. try: qry = "UPDATE fhc_imp_glidepath_initiatives SET canceller = 'tan.gt.1', end_date = '05/04/2024 10:08:03' WHERE uid = '2'" conn = sa.create_engine(f'postgresql://{user}:{pwd}@{srv}:{port}/{db}') cursor = conn.cursor() cursor.execute(qry) conn.commit() return True except Exception as e: print(e) return False What will be the solution or proper query to fix this? Thank you in advance. Expecting to fix the AttributeError regarding cursor and execute when using sqlalchemy 2.0.29 and knowing what's the correct syntax to use in this type of situation. -
issue in Django 5.0.2 and django_rest_framework
hi guys i have issue with reading sql data from postgresql with django. i created my model with manage.py inspectdb command from existing database. my model: from django.db import models class Regions(models.Model): code = models.CharField(unique=True, max_length=4) capital = models.CharField(max_length=10) name = models.TextField(unique=True) class Meta: managed = False db_table = "regions" My serializer: from rest_framework import serializers class RegionsSerializer(serializers.ModelSerializer): class Meta: model = "france.models.Regions" fields = "__all__" my viewset: from rest_framework import viewsets from rest_framework.response import Response from .models import Regions from .serializers import RegionsSerializer class RegionsView(viewsets.ViewSet): def list(self, request): regions = Regions.objects.all() serializer = RegionsSerializer(regions, many=True) return Response(serializer.data) and error i get: AttributeError at /regions/ 'str' object has no attribute '_meta' Request Method: GET Request URL: http://127.0.0.1:1000/regions/ Django Version: 5.0.4 Exception Type: AttributeError Exception Value: 'str' object has no attribute '_meta' Exception Location: C:\Projects\play_ground\python\django_one\venv\Lib\site-packages\rest_framework\utils\model_meta.py, line 35, in get_field_info Raised during: france.views.RegionsView Python Executable: C:\Projects\play_ground\python\django_one\venv\Scripts\python.exe Python Version: 3.12.2 Python Path: ['C:\\Projects\\play_ground\\python\\django_one', 'C:\\Users\\safkh\\AppData\\Local\\Programs\\Python\\Python312\\python312.zip', 'C:\\Users\\safkh\\AppData\\Local\\Programs\\Python\\Python312\\DLLs', 'C:\\Users\\safkh\\AppData\\Local\\Programs\\Python\\Python312\\Lib', 'C:\\Users\\safkh\\AppData\\Local\\Programs\\Python\\Python312', 'C:\\Projects\\play_ground\\python\\django_one\\venv', 'C:\\Projects\\play_ground\\python\\django_one\\venv\\Lib\\site-packages'] Server time: Fri, 05 Apr 2024 08:19:46 +0000 can you help me with issue thnx all -
Question about auto re-issue Access token in Django (simple jwt)
Hello I have a question about JWT in backend django, so I'm leaving a question. (I'm using Simple-jwt package.) Currently, when the user logs in, both access and refresh tokens are being sent to the response body. (I'm trying to send refresh tokens to the header because there's a security problem.) At this time, when the access token expires, I know the procedure to reissue it through refresh, but I don't know how django will handle it automatically. I wanted to go to the procedure of reissuance before the expiration time of access at the front(web/app), but there is a problem that the access token increases indefinitely. When the front sends a general API request, I know that if client send both access and refresh, the access token will expire through the IsAuthenticated procedure at the back server, and I understand that it automatically reissues the access token through refresh and performs the previously requested API. So I tried Googling this, but I didn't see the code that automatically reissued it, only sending it to the endpoint (/jwt-token-auth/refresh/) provided by default. However, if I get caught in IsAuthenticated, the server spit out the error because it's invalid token, how do … -
How do I create separate fields for normal users and admins users in Django?
I have a custom user model that has fields common for both a normal user and an admin (which are email[used to log into the system], first name, and last name). But I want to give additional fields for the normal users of the system. How do I achieve this? class UserAccountManager(BaseUserManager): def create_user(self, email, first_name, last_name, password=None): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) email = email.lower() user = self.model( email=email, first_name=first_name, last_name=last_name ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name, password=None): user = self.create_user(email, first_name, last_name, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) profile_picture = models.ImageField(default='default.jpg', upload_to='profilePictures', null=True, blank=True) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return self.email + " | " + self.first_name Ii tried the above code but it only create a one single table for both normal users and admins -
Unable to fetch data from django to react
So I am creating a login page. I have created my models as well as the views and endpoints. When logging in, I was trying to fetch the data from the backend using django to verify the login credentials entered, But I get a runtime error TypeError: Failed to fetch at HandleSubmit I am successful in registering my user, I have checked in the database to make sure that the user exists A basic overview of my setup. I have a model LoginDetails, which has been set as the AUTH_USER_MODEL in settings.py. Here is my model class LoginDetails(AbstractUser): user_data = models.OneToOneField(UserData, on_delete=models.CASCADE, null = True) username = models.CharField(max_length=255, unique=True, null=True) password = models.CharField(max_length=255, null=True) # Note: It's recommended to use hashed passwords in production USERNAME_FIELD = 'username' def __str__(self): return self.username Here is my login.js (Only posting the relevant info) `const handleSubmit = async (event) => { event.preventDefault(); const response = await fetch('http://127.0.0.1:8000/api/login/', { method: 'POST', headers: {'Content-Type': 'application/json'}, credentials: 'include', body: JSON.stringify({ formData }) }); const content = await response.json(); setRedirect(true); props.setName(content.name); };` And the view associated with my endpoint api/login class LoginView(APIView): def post(self, request): username = request.data.get('username') password = request.data.get('password') user = LoginDetails.objects.filter(username=username).first() if user is None: … -
HTML Content is not loading in Django Application
See in the image, my html content is not loading in django project Till yesterday it was working fine. dont know what happened in a night. Noone has touched my PC but dont know why am I getting this issue. Please help me. This is very urgent -
How can I solve N+1 problem double prefetch_related using order_by in Django?
In models.py the simple structure is... Model A(parent of B) <- Model B(parent of C) <- Model C And in views.py, I want to use both prefetch_related in B,C and order_by in b. a_obj = A.objects.prefetch_related(Prefetch("b__c", queryset=B.objects.all().order_by("-order"))) but in serializers.py, I cannot access to c's data. def get_data(self, group): for b in group.b.all(): print(b.c.all()) # ===> result: queryset [B object(pk)] And I also tried another way in views.py and serializers.py # views.py a_obj = A.objects.prefetch_related("b__c") # serializers.py def get_data(self, group): for b in group.b.all().order_by("-order"): print(b.c.all()) # ===> N+1 query occurred But I have N+1 problem. What should I do? -
Django 5: Within the form, filter data with another field of the same form
I have a question that I can't solve. Form: I choose country I choose region 1 I choose region 2 Based on the country I chose, how can I filter the data for region 1? Code fk_country = forms.ModelChoiceField( label="Pais", queryset= PteCountry.objects.all(), required=True, error_messages={"required": "Introduzca Pais"}, ) fk_region_1 = forms.ModelChoiceField( label="Region 1", queryset= PteRegion1.objects.filter(fk_country_id__in=PteCountry.objects.filter(id=**?????**).values_list('id')), required=True, error_messages={"required": "Introduzca Region 1"}, ) filter a list of values, based on a field of the same form -
annotating an object with a list of objects related to it but filtered down
I have the following objects (simplified just for this question) class Object1(models.Model): users_assigned_to_object1 = models.ManyToMany(Users, related_name='objects') sub_object = models.ForeignKey(SubObject1) class Users(models.Model): first_name = models.CharField(max_length=1000) class SubObject1(models.Model): sub_object_name = models.CharField(max_length=1000) class SubObject2(models.Model): sub_object_1 = models.ManyToMany(SubObject1) class SubObject3(models.Model): sub_object_2 = models.ManyToMany(SubObject3) role_name = models.CharField(max_length=1000) user = models.ForeignKey(Users, related_name='sub_object_relation') For more complex reasons that do not matter right now, I need to be able to annotate Object1 with the users that are users assigned to object 1 AND where those users have role_name=ADMIN for at least one of the SubObject3 models that are related to Object1. E.g. I'm trying to get to something like this: Object1.objects.annotate(admin_users=X) What goes on X? I'm on Django 4.2 and using a Postgres DB I tried using SubQueries but they don't respond with lists (and this can return a list) and tried doing things with Django Conditional expressions (e.g. ArrayAgg, When) but couldn't really get to the right solution on this one. -
Field 'id' expected a number but got dict when seeding database django
I'm looking for a way to store a question fetched from an external API to be stored in a model called Question. My views.py module does that by requesting data based on user's question difficulty choice, then renders what's fetched in a form. It's a pretty straightforward method but for some reason I get Field 'id' expected a number but got {'type': 'multiple'...}. I deleted a code that intended to create a another model singleton that was interfering with this implementation from last answer of this question. Then I ran ./manage.py makemigrations and ./manage.py migrate to reflect changes but the exception was again raised. After that, I deleted migrations.py and their cached files to run the same two commands and nothing changed. Can anyone point out what I'm missing/doing wrong please? models.py from django.db import models class Question(models.Model): type = models.TextField() difficulty = models.TextField() category = models.TextField() question = models.TextField() correct_answer = models.TextField() incorrect_answers = models.TextField() views.py from django.shortcuts import render, HttpResponse from .forms import QuestionForm, QuestionLevelForm from urllib.request import URLError from .models import Question import requests def process_question(request): if "level" in request.POST: return fetch_question(request) elif "answer" in request.POST: return check_answer(request) else: form = QuestionLevelForm() return render(request, "log/question.html", {"form": form}) … -
Return http status code 401 when login with invalid credentials
How would i go about changing an django application that uses allauth so that it returns 401 response when invalid login credentials are provided? I have tried to put custom logic in a custom ModelBackend but found no way to actually modify the response status code there. I have also tried to put custom logic in a CustomAccountAdapter.authentication_failed but same issue there i found no way to change the status code. -
Please how to I fix primary key url issue in Django
I decided working of an API using Django Rest Framework and I can be able to view all the data in the endpoint but when I try to call just one of the data using a primary in the URL, I get a 404 error These are my codes. Please I need help[[[[[[Codes and the error dispayed](https://i.stack.imgur.com/yzFca.jpg)](https://i.stack.imgur.com/kbBLY.jpg)](https://i.stack.imgur.com/bSHbk.jpg)](https://i.stack.imgur.com/hjn9A.jpg)](https://i.stack.imgur.com/5E2WX.jpg)](https://i.stack.imgur.com/gdnVC.jpg) -
Django admin add form produces TypeError: __str__ returned non-string (type __proxy__)
I got the followin error message and I do not understand the issue. Further, I do not know where to start my search. TypeError at /admin/fixeddata/persondetails/add/ str returned non-string (type proxy) Request Method: GET Request URL: http://127.0.0.1:8000/admin/fixeddata/persondetails/add/ Django Version: 5.0.4 Exception Type: TypeError Exception Value: str returned non-string (type proxy) Exception Location: C:\Projects\Plattform\venv\Lib\site-packages\django\forms\models.py, line 1523, in label_from_instance Raised during: django.contrib.admin.options.add_view Python Executable: C:\Projects\Plattform\venv\Scripts\python.exe Python Version: 3.11.1 Python Path: ['c:\Projects\Plattform\project', 'C:\Python\python311.zip', 'C:\Python\DLLs', 'C:\Python\Lib', 'C:\Python', 'C:\Projects\Plattform\venv', 'C:\Projects\Plattform\venv\Lib\site-packages'] Server time: Thu, 04 Apr 2024 20:46:57 +0200 I already used str() in all my overrides of the str method of my model classes. I do not know what the "type proxy" means and when proxy is returned. In a forum entry I read something about a potential conflict with the gettext_lazy method. I use that as well in my model class. I tried to import gettext instead but that the error remains unchanged. I do not know for what type of error I am looking. It would be great if anyone could give me a hint.