Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why can’t I deactivate the virtual environment?
here is my problem that didn't help either and it is now in double brackets, and not in single brackets as before -
Django coverage test doesn't seem to run all app tests
I am using coverage to check how much code I have covered with my test suite. It seems to not run some tests when I run the complete test suite but does if I only run an app. For example coverage run manage.py test followed by covereage html shows the api app has a 24% coverage. But when I run coverage run manage.py test api followed by coverage html I get 100% covered. Why would this happen? -
Upgrade graphene-django to v3: 'Int cannot represent non-integer value"
I'm trying to upgrade graphene-django from 2.15.0 to 3.2.0. After some fixes, I could get it to work, but while testing with the front-end, I start detecting errors of the type: "Variable '$height' got invalid value '5'; Int cannot represent non-integer value: '5'" Apparently graphene-django 2.15 can translate string arguments (in this case '5') into number values, but 3.2 it can't. Is there a way to adapt the back-end so I don't have to change the front-end to correct the strings and turn them into numbers? -
Django + react with apache can't find django rest api
I have a django + react app that i wish to deploy on my VPS. I've installed apache for that and tried to configure it to work with django and react. When i only put django in the apache conf it does work with a curl command to the django api and react always works fine. But when putting django and react together in the conf file in apache it seems like when making post or get requests to the api it doesn't find the django api. Here is my app.conf in apache : <VirtualHost *:80> ServerName vps-*******.vps.ovh.net WSGIDaemonProcess app python-path=/home/gabriel/scanner:/home/gabriel/venv/lib/python3.11/site-packages WSGIProcessGroup app WSGIScriptAlias /api /home/gabriel/scanner/App/wsgi.py <Directory /home/gabriel/scanner/App> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static /home/gabriel/scanner/staticfiles <Directory /home/gabriel/scanner/staticfiles> Require all granted </Directory> Alias /static-react /home/gabriel/scanner/frontend/build/static <Directory /home/gabriel/scanner/frontend/build/static> Require all granted </Directory> <Directory /home/gabriel/scanner/frontend/build> Options FollowSymLinks Require all granted RewriteEngine on RewriteCond %{REQUEST_URI} !^/api RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> CORS is allowed for all origins in my settings.py in django for testing and the whole settings.py file seems nicely configured. wsgy.py is nicely configured too and here is my urls.py : from django.contrib import admin from django.urls … -
Nginx can't serve Django url over Gunicorn Docker container
I am trying to deploy my Django Docker application with Nginx and Gunicorn.I followed this tutorial.I also managed to run my Django app on :8000 and Nginx on :80, I can reach both :80 and :8000 but when I try to connect to for example :80/app I just get a 404, at the same time I can connect to :8000/app. My main Docker File looks like: FROM python:3.10.6-alpine RUN pip install --upgrade pip COPY ./requirments.txt . RUN pip3 install -r requirments.txt COPY ./proto /app WORKDIR /app COPY ./entrypoint.sh / ENTRYPOINT [ "sh", "/entrypoint.sh" ] this run my entrypoint.sh: python manage.py migrate --no-input python manage.py collectstatic --no-input gunicorn proto.wsgi:application --bind 0.0.0.0:8000` and my compose.yml looks like: version: '3.7' services: django_proto: volumes: - static:/static env_file: - .env build: context: . ports: - "8000:8000" nginx: build: ./nginx volumes: - static:/static ports: - "80:80" depends_on: - django_proto volumes: static: and my default.conf: upstream django { server django_proto:8000; } server { listen 80; location /static/ { alias /app/static; } location / { proxy_set_header Host $http_host; proxy_pass http://django; proxy_redirect off; } } I tried different folder constructs because I thought I was just trying to connect to the wrong folder path, I also tried different ports … -
Code on Django does not reflect on the created website
I'm currently learning how to use django so I watch a youtube video and its Tech with Tim. His tutorials are good and I followed all his instructions but unfortunately, I did not get the expected result. I try asking chatgpt but somehow it cannot help me to fix this problem. Please help me on this problementer image description hereenter image description hereenter image description here the problemproblem error 404 -
Unable to create a django project showing attribute error in django5.0
I am new to django while using django version 1.11.29 it worked successful when upgraded to latest version 5.0.4 it not working and showing error as below try this on venv shown same result is problem with python ,my python version 3.13.0a5+ I was tried to get django versio by python3 -m django --version it has been shown no module named django found -
Speed up problem with response Django REST API
We are got a project on gunicorn,django and nginx. Got a table in postgres with 600000 records with a big char fields(about 7500). That problem solved by triggers and searchvector. Also there api(rest) and 1 endpoint. On this endpoint db request take about 0.3 s. Its normal for us. But getting response take about 2 minutes.While we are waiting for a response one of process(they are a 8 cores) take about 100%. CPU User CPU time 201678.567 ms System CPU time 224.307 ms Total CPU time 201902.874 ms TOTAL TIME 202161.019 ms SQL 385 ms What we can to do to speed up time of response? I tryed to change settings if gunicorn,but that doesnt help. Than I try to start project by ./manage.py runserver on unused port and send request to endpoint and got the same results of time. I think the problem with view of REST API django. Django work with asgi now ,gunicorn and nginx. -
how to apply vuexy theme in django application
how to apply vuexy theme in django application? I want to apply vuexy theme in my django project can you tell me any documentation or guidence how to apply vuexy theme in django application? I want to apply vuexy theme in my django project can you tell me any documentation or guidence properway -
Failed to load module script: help needed
index-d5Zm7UFq.js:1 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec I am doing react+vite as frontend and django and mysql as backend. It runs without problem in localhsot:5173, but when i run on localhost:8000 it is showing this error, what i did was after building dist, i copied dist folder and pasted it on backend. I aslo configured settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'dist')] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles') MEDIA_URL = '/media/' I aslo setup urls.py: from django.urls import path, include, re_path from django.views.generic import TemplateView urlpatterns = [ path('auth/', include('djoser.urls.jwt')), re_path(r'^.*$', TemplateView.as_view(template_name='index.html')), path('vite.svg', TemplateView.as_view(template_name='vite.svg')), ] And it is showing blank when i access localhost:8000,and there is this error in console: Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec. -
Problem when integrating django project with deep learning model using h5 file
after i make all things in django project and have the h5 file of deep learning model using CNN , and when running the development server , and uploading image , the view function code import os import numpy as np from django.shortcuts import render, redirect from .forms import ImageUploadForm from .models import UploadedImage from tensorflow.keras.models import load_model from PIL import Image def upload_image(request): if request.method == 'POST': form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): image_instance = form.save() image_path = os.path.join('media', str(image_instance.image)) prediction = predict_disease(image_path) return render(request, 'prediction_result.html', {'prediction': prediction}) else: form = ImageUploadForm() return render(request, 'upload_image.html', {'form': form}) def predict_disease(image_path): model = load_model(r'C:\Users\pc\PycharmProjects\testingModelH5\models\EfficientNetB1-Skin-disease-b1-87.h5') image = Image.open(image_path) image = image.resize((224, 224)) image_array = np.array(image) / 255.0 image_array = np.expand_dims(image_array, axis=0) prediction = model.predict(image_array) return prediction the error occurs below Error when deserializing class 'DepthwiseConv2D' using config={'name': 'block1a_dwconv', 'trainable': True, 'dtype': 'float32', 'kernel_size': [3, 3], 'strides': [1, 1], 'padding': 'same', 'data_format': 'channels_last', 'dilation_rate': [1, 1], 'groups': 1, 'activation': 'linear', 'use_bias': False, 'bias_initializer': {'module': 'keras.initializers', 'class_name': 'Zeros', 'config': {}, 'registered_name': None}, 'bias_regularizer': None, 'activity_regularizer': None, 'bias_constraint': None, 'depth_multiplier': 1, 'depthwise_initializer': {'module': 'keras.initializers', 'class_name': 'VarianceScaling', 'config': {'scale': 2.0, 'mode': 'fan_out', 'distribution': 'truncated_normal', 'seed': None}, 'registered_name': None}, 'depthwise_regularizer': None, 'depthwise_constraint': None}. Exception encountered: Unrecognized keyword … -
is it necessary to use https instead of http to connect RN app with Django using axios?
i have been trying to send the post request to django using axios but it keeps showing axios; network error this below is axios.js import axios from "axios" import { Platform } from 'react-native'; const BASE_URL = Platform.OS === 'android' ? "https://10.0.2.2:8000" : "https://localhost:8000"; export const axiosInstance = axios.create({ baseURL: `${BASE_URL}`, headers: { } }) and RN app import React, { useState, useEffect } from 'react'; import { View, Text, Image, Alert, StyleSheet, TouchableOpacity, Platform } from 'react-native'; import axios from 'axios'; import * as ImagePicker from 'expo-image-picker'; import { Icon, Button } from '@rneui/themed'; const FoodPredictionScreen = ({ navigation }) => { const [prediction, setPrediction] = useState(''); const [imageUri, setImageUri] = useState(null); useEffect(() => { (async () => { if (Platform.OS !== 'web') { const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync(); if (status !== 'granted') { alert('Sorry, we need camera roll permissions to make this work!'); } } })(); }, []); useEffect(() => { console.log('Image URI state updated:', imageUri); }, [imageUri]); const selectImage = async () => { try { let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.Images, allowsEditing: true, aspect: [6, 5], quality: 1, }); if (!result.cancelled) { setImageUri(result.assets[0].uri); console.log('Selected Image URI:', result.assets[0].uri); // Corrected line } } catch … -
Django (beginner) How Serialize several models
REAL PROBLEM: On DJANGO, I Have Several models,with some fiels such as MODEL1: NAME = ADDRESS = MODEyour textL2: NAME = ADDRESS = PET_NAME = MODEL3: NAME = ADDRESS = PET_NAME = BEER = I intent to use it as a parameter on GeoJSONLayerView.as_viewd. MY SOLUTION(?) How to get a 'MODEL' type with fields NAME and ADDRESS from ALL models, serialized? (Must be a MODEL, if using GeoJSONLayerView) Like a Sql select NAME, ADDRESS from MODEL1, MODEL2, MODEL3 How to get a MODEL with fields from seleral MODELS. -
Django Channels Config - Django / Docker / Gunicorn / Daphne / Nginx
I have deployed an app, pypilot.app using django / nginx / docker / daphne / gunicorn on a digital ocean droplet. Daphne is for Django Channels which works no problem in development to display messages in a user's console via websocket. I'm also able to connect to the websocket successfully when navigating to my droplet's IP address over http. When I try to connect to websocket via https at pypilot.app, however, I run into issues. I suspect something is wrong with my ssl setup perhaps? Please let me know if you spot any obvious issues in my setup below. docker compose version: '3' services: web: build: . command: gunicorn unicorn_python.wsgi:application --bind 0.0.0.0:8000 volumes: - .:/code - .:/usr/src/app - /var/run/docker.sock:/var/run/docker.sock ports: - "8000:8000" daphne: build: . volumes: - .:/usr/src/app - .:/code ports: - "8001:8001" command: daphne -b 0.0.0.0 -p 8001 unicorn_python.asgi:application nginx: image: nginx:latest ports: - "80:80" - "443:443" volumes: - ./config/nginx:/etc/nginx/conf.d - /etc/letsencrypt:/etc/letsencrypt:ro - ./static:/usr/src/app/static # Host path to static files mounted inside the container - ./media:/usr/src/app/media # Host path to static files mounted inside the container depends_on: - web - daphne # If Nginx is set to proxy to Daphne as well celery: build: . command: celery -A unicorn_python … -
Django request.user isn't using the custom backend at all
I'm coding with a custom user model and a custom backend in Django 5.0 to login with an email. Here is the backend : class EmailBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): print("authenticate called") try: user = User.objects.get(email=username) except User.DoesNotExist: return None else: if user.check_password(password): return user return None def get_user(self, user_id): try: print(user_id) print("get_user called") return User.objects.get(pk=user_id) except User.DoesNotExist: return None It's correctly registered in AUTHENTICATION_BACKENDS, and the user model just have an email field. The backend works perfectly in my register view using authenticate(request, username=email, password=password), and the login(request, user) works too. However, if in another view, after a login I try to use request.user, it will always return AnonymousUser. If I do request.session.values, the user ID is correct. I can't find anyone having the same issue online, so I hope someone can help me troubleshoot it. I tried to use request.user with the custom backend, but it's never called. I also tried to use request.session.values and this time the user ID was correct. The request.user was supposed to return the current user with my custom model, but it always return AnonymousUser -
Detect if a Django related object has been prefetched via select_related
Let's say I have the following models: class Product: name = models.CharField(max_length=128) class ProductVersion: name = models.CharField(max_length=128) product = models.ForeignKey(Product, on_delete=models.CASCADE) For a given ProductVersion object, is there anyway to detect if the Product object was prefetched via select_related? For example: # Yes, "product" was prefetched ProductVersion.objects.select_related("product").first() # No, "product" was NOT prefetched ProductVersion.objects.first() Looks like there's a way to do this was prefetch_related (see here) but I need it for selected_related. -
Django / Celery : How a task can constantly do something ? Is it possible to set an infinite loop for a task?
I'm currently learning Django and Celery. So I have to do a feature to a Django projet, and I use Celery for that : I need to constantly check a list in my Redis server. And for that, I use Celery but I don't know how I can implement correctly that and I opted for a while True:. After the launching of my task with celery -A <my_project> worker -l INFO, it's impossible to kill the task (the CTRL + C doesn't work), or I don't found how I can. I conclude it's not a good method for doing what I want. One more thing : I know the extension django-celery-beat exists but I think it's "weird" to open another terminal for launch this extension. Already I have to launch my django server, then my worker (with celery) on two different terminals, I have to open a third to launch my scheduled task, I don't know if this is really weird to do that, but... I don't know, I think it's weird to do that but I don't know if it really is. Here's my (unique) task in an app in my django project : from celery import shared_task import … -
Rewrite User logic in Django
I need to completely rewrite the user logic in Django. I would like to store only 2 parameters in the database: phone number and telegram_id. The user could login and register with both of these parameters from one page. So I need to rewrite the model and write custom views and urls. The main question is how do I write a user model from scratch, replacing the standard django one. However, I wouldn't want to completely remove the user block and write it from scratch. Just models and some views and urls Search the internet. -
Issue running python3 manage.py makemigrations
(C7M5L1-6 Lab Initial) kennyc@Kennys-MacBook-Pro C7M5L1-6 Lab Initial % brew install mysql-client ==> Downloading https://formulae.brew.sh/api/formula.jws.json ############################################################################################# 100.0% ==> Downloading https://formulae.brew.sh/api/cask.jws.json ############################################################################################# 100.0% Warning: mysql-client 8.3.0 is already installed and up-to-date. To reinstall 8.3.0, run: brew reinstall mysql-client (C7M5L1-6 Lab Initial) kennyc@Kennys-MacBook-Pro C7M5L1-6 Lab Initial % python3 manage.py makemigrat ions Traceback (most recent call last): File "/Users/kennyc/.local/share/virtualenvs/C7M5L1-6_Lab_Initial-6eeCEMqS/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/kennyc/.local/share/virtualenvs/C7M5L1-6_Lab_Initial-6eeCEMqS/lib/python3.9/site-packages/MySQLdb/__init__.py", line 17, in <module> from . import _mysql ImportError: dlopen(/Users/kennyc/.local/share/virtualenvs/C7M5L1-6_Lab_Initial-6eeCEMqS/lib/python3.9/site-packages/MySQLdb/_mysql.cpython-39-darwin.so, 0x0002): symbol not found in flat namespace '_mysql_affected_rows' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/kennyc/Desktop/C7M5L1-6 Lab Initial/manage.py", line 22, in <module> main() File "/Users/kennyc/Desktop/C7M5L1-6 Lab Initial/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/kennyc/.local/share/virtualenvs/C7M5L1-6_Lab_Initial-6eeCEMqS/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/Users/kennyc/.local/share/virtualenvs/C7M5L1-6_Lab_Initial-6eeCEMqS/lib/python3.9/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/Users/kennyc/.local/share/virtualenvs/C7M5L1-6_Lab_Initial-6eeCEMqS/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/kennyc/.local/share/virtualenvs/C7M5L1-6_Lab_Initial-6eeCEMqS/lib/python3.9/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Users/kennyc/.local/share/virtualenvs/C7M5L1-6_Lab_Initial-6eeCEMqS/lib/python3.9/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File … -
OpenAI API Integration in Django: Request Getting Lost on Server
I have integrated the OpenAI API into my Django project for generating dynamic descriptions for tables generated in my application. The workflow involves processing user input, generating tables, and then passing these tables to the OpenAI API one by one using client.chat.completions.create. While this works smoothly on my local system, when deployed on the server, the request sometimes seems to get lost at the point of calling client.chat.completions.create. It returns the response processed until that stage, rather than waiting for the completion response from the OpenAI API. try: chat_completion = client.chat.completions.create( messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": prompt}, ], model="gpt-3.5-turbo", temperature=0.5, max_tokens=1024 ) logger.info('---- GPT4') logger.info("chat completion",chat_completion.choices[0].message.content) response_content = chat_completion.choices[0].message.content logger.info('---- GPT5') except Exception as e: logger.info('---- Error in chat gpt "',str(e)) pass Upon debugging, it seems that the request doesn't wait for the response from client.chat.completions.create, causing it to return incomplete responses on the server. What could be causing this behavior, and how can I ensure that the request waits for the completion response from the OpenAI API before proceeding further? Any insights or suggestions would be greatly appreciated. Thank you! -
Heroku app unable to import Django, using requirements/Aptfile/Procfile
I have a django server that works locally but I am having a really tough go of trying to get Heroku to deploy it. The error I constantly get no matter what I try is Traceback (most recent call last): File "/app/manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 21, in <module> main() File "/app/manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? After reading various similar questions around here, I decided to try setting PYTHONPATH to '/app' (after first reducing manage.py to a 'hello world' so heroku would let me change config vars) so I got that set up and then restored manage.py, only to receive the same error. Build always succeeds, release always fails. manage.py, requirements.txt, runtime.txt, Procfile and Aptfile are all on the root directory. manage.py is unmodified from the default. The contents of the other files: requirements.txt: asgiref==3.7.2 certifi==2023.7.22 distlib==0.3.8 django==5.0 django-cors-headers==4.3.1 djangorestframework==3.14.0 djangorestframework-simplejwt==5.3.1 filelock==3.13.1 mysqlclient==2.2.1 platformdirs==4.1.0 protobuf==4.24.4 PyAudio==0.2.14 … -
Exception Value: Field 'id' expected a number but got 'count'
ValueError at /cart/LFzsWGDl13fxCZP/ Field 'id' expected a number but got 'count'. Request Method: POST Request URL: http://127.0.0.1:8000/cart/LFzsWGDl13fxCZP/ Django Version: 5.0.4 Exception Type: ValueError Exception Value: Field 'id' expected a number but got 'count'. Exception Location: C:\Users\Next Nout\Documents\NT\Najot talim vazifa\7-oy\8-dars\shop\env\Lib\site-packages\django\db\models\fields_init_.py, line 2119, in get_prep_value Raised during: main.front.views.cart_detail Python Executable: C:\Users\Next Nout\Documents\NT\Najot talim vazifa\7-oy\8-dars\shop\env\scripts\python.exe Python Version: 3.12.0 Python Path: ['C:\Users\Next Nout\Documents\NT\Najot talim vazifa\7-oy\8-dars\shop', 'C:\Users\Next ' 'Nout\AppData\Local\Programs\Python\Python312\python312.zip', 'C:\Users\Next Nout\AppData\Local\Programs\Python\Python312\DLLs', 'C:\Users\Next Nout\AppData\Local\Programs\Python\Python312\Lib', 'C:\Users\Next Nout\AppData\Local\Programs\Python\Python312', 'C:\Users\Next Nout\Documents\NT\Najot talim ' 'vazifa\7-oy\8-dars\shop\env', 'C:\Users\Next Nout\Documents\NT\Najot talim ' 'vazifa\7-oy\8-dars\shop\env\Lib\site-packages'] Server time: Sun, 07 Apr 2024 18:16:06 +0000 **@login_required(login_url='auth:login') def cart_detail(request, code): cart = models.Cart.objects.get(code=code) queryset = models.CartProduct.objects.filter(cart=cart) if request.method == 'POST': data = list(request.POST.items())[1::] for id,value in data: cart_product = models.CartProduct.objects.get(id=id) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … cart_product.count = value cart_product.product.quantity -= int(value) cart.status = 2 cart_product.product.save() cart.save() cart_product.save()** -
How not to save data from Inline Django Model?
I'm trying to implement the ability to view users' locations in a task through the inline Geoposition model. Geoposition stores latitude and longitude, then thanks to changing the tabular.html template I display the map When I try to save the model, I get an error: The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS, because data from this Geoposition inline trying to POST. I would not like to change this setting. In this case, the inline model class looks like this class TaskTransitInline(admin.TabularInline): template = "admin/gis/tabular_override.html" model = Geoposition extra = 0 max_num = 0 can_delete = False fields = ( "id", "task", "created_at", "longitude", "latitude", "speed", ) readonly_fields = ["id", "task", "created_at", "longitude", "latitude", "speed"] Why do I then see ID and task in the data POST? Maybe someone can help me -
Problem with pip install (FileNotFoundError: [Errno 2] No such file or directory: 'requirements.txt')
I wanted to use contributions graph in my Django project, so after quick research I decided to use 'contributions-django' library. But when I tried to install it, I got stuck with this error:: FileNotFoundError: [Errno 2] No such file or directory: 'requirements.txt' [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. I am no pip expert, but I can see that requirements.txt file exists in this repository (altough it's empty). How to fix this? Can I install the libary manually? How? Thanks for help in advance. -
Django QuerySet: how to aggregate repeated elements and add quantity field to it?
I have a feeling the solution to this is very simple, but as new to Django I am not able to figure it out... Given the following QuerySet: <QuerySet [ {'id': 2, 'prodclassQuery_id': 1, 'prodDescription': 'Hofbräu Kellerbier 500 ml', 'prodPrice': Decimal('6.50')}, {'id': 1, 'prodclassQuery_id': 1, 'prodDescription': 'Tonic Water 300 ml', 'prodPrice': Decimal('4.50')}, {'id': 3, 'prodclassQuery_id': 2, 'prodDescription': 'Coxinha 6 unidades', 'prodPrice': Decimal('8.00')}, {'id': 3, 'prodclassQuery_id': 2, 'prodDescription': 'Coxinha 6 unidades', 'prodPrice': Decimal('8.00')}]> I want to aggregate the repeated elements (based on id) e produce the following QuerySet, adding the field poQty_ to represent the quantity of repeated elements (products in my case...): <QuerySet [ {'id': 2, 'prodclassQuery_id': 1, 'prodDescription': 'Hofbräu Kellerbier 500 ml', 'prodPrice': Decimal('6.50'), 'poQty_': 1}, {'id': 1, 'prodclassQuery_id': 1, 'prodDescription': 'Tonic Water 300 ml', 'prodPrice': Decimal('4.50'), 'poQty_': 1}, {'id': 3, 'prodclassQuery_id': 2, 'prodDescription': 'Coxinha 6 unidades', 'prodPrice': Decimal('8.00'), 'poQty_': 2}]> What I tried so far with annotate() in views.py is not working, and the results of orders_aggris the same original QuerySet: def display_orders(request): orders = Order.objects.all().order_by('id', 'orderTable', 'menuQuery') for j in orders: print(j.prodQuery.values(),) # original QuerySet orders_aggr = Order.objects.annotate(poQty_=Count('prodQuery__id')).order_by('id', 'orderTable', 'menuQuery') for j in orders_aggr: print(j.prodQuery.values(),) context = { 'orders': orders, 'orders_aggr': orders_aggr } return render(request, 'orders.html', context) …