Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to include Django CSRF token in JavaScript API fetch?
I created simple API in Django and I need to fetch it with JavaScript, I get following error: Forbidden (CSRF token missing.): URL(placeholder instead of real url) fetch(`/Post/${content[i].id}`, { method: "POST", }).then((data) => { console.log(data); }) How can I include token in API call? -
Error installing django-mssql, pyodbc in django
I am trying to install mssql-django package to my EC2(ubuntu) Server so that I connect my application to sql server But I got stuck while installing mssql-django with an error with pyodbc message is below pipenv.exceptions.InstallError]: warnings.warn( [pipenv.exceptions.InstallError]: running build [pipenv.exceptions.InstallError]: running build_ext [pipenv.exceptions.InstallError]: building 'pyodbc' extension [pipenv.exceptions.InstallError]: In file included from src/buffer.cpp:12:0: [pipenv.exceptions.InstallError]: src/pyodbc.h:45:10: fatal error: Python.h: No such file or directory [pipenv.exceptions.InstallError]: #include <Python.h> [pipenv.exceptions.InstallError]: ^~~~~~~~~~ [pipenv.exceptions.InstallError]: compilation terminated. [pipenv.exceptions.InstallError]: error: command '/usr/bin/x86_64-linux-gnu-gcc' failed with exit code 1 [pipenv.exceptions.InstallError]: [end of output] [pipenv.exceptions.InstallError]: [pipenv.exceptions.InstallError]: note: This error originates from a subprocess, and is likely not a problem with pip. [pipenv.exceptions.InstallError]: error: legacy-install-failure [pipenv.exceptions.InstallError]: [pipenv.exceptions.InstallError]: × Encountered error while trying to install package. [pipenv.exceptions.InstallError]: ╰─> pyodbc [pipenv.exceptions.InstallError]: [pipenv.exceptions.InstallError]: note: This is an issue with the package mentioned above, not pip. [pipenv.exceptions.InstallError]: hint: See above for output from the failure. ERROR: Couldn't install package: pyodbc Package installation failed... ☤ ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 0/1 — 00:00:03 I am using python 3.8 in pipenv and I think I tried everything Including pip install pyodbc, sudo apt install unixodbc-dev. Please Help.. -
React is not showing posts of request.user in Django Rest Framework
I am building a Blog App in Django and React and I am trying to get posts only of request.user, and In Django Rest Framework Dashboard (api as json) posts are perfectly showing of request.user But when i try with axios.get() in React Frontend then it is showing nothing. views.py class BlogView(viewsets.ModelViewSet): serializer_class = BlogSerializer def get_queryset(self): queryset = Blog.objects.filter(user_id=self.request.user.id) return queryset serializers.py class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog fields = ('id','user'','title', 'description') React - App.js componentDidMount() { let data; axios.get('http://127.0.0.1:8000/api/blogs/`).then((res) => { data = res.data; this.setState({ blogs : data.map((blog) => { return Object.assign({}, blog, { title : blog.title, description : blog.description, }); }), }); }) .catch(err => {console.log(err)}); }; I have tried many times but accessing it using filter(user=self.request.user) but it didn't worked for me. When I refresh React Page then it is showing [16/Feb/2022 14:05:21] "GET /api/blogs/ HTTP/1.1" 200 2 in Django Server. Any help would be much Appreciated. Thank You in Advance. -
Django - display "work-in-progress" after submitting form until result is returned
I have a online pricing webpage where customer can input some data, then submit the form to get the price returned. How to display a "work-in-progress" kind of thing temporarily before the final result (e.g. price) is calculated/returned. below is the simplified code from my web: html (Note: I am using htmx to help partially update the page result) <html> <body> <form method="POST" hx-post="{% url 'post_list' %}" hx-target="#num_1" hx-target="#num_2" hx-target="#result"> {% csrf_token %} <div> <label>num_1:</label> <input type="text" name="num_1" value="" placeholder="Enter value" /> </div> <div> <label>num_2:</label> <input type="text" name="num_2" value="" placeholder="Enter value" /> </div> <br /> <div id="num_1">{{ num_1 }}</div> <br /> <div id="num_2">{{ num_2 }}</div> <br /> <div id="result">{{ result }}</div> <br> <button type="submit">Submit</button> </form> <script src="https://unpkg.com/htmx.org@1.6.1"></script> </body> </html> view.py def post_list(request): result = "" num1 = "" num2 = "" if request.method == "POST": num1 = request.POST.get('num_1') num2 = request.POST.get('num_2') result = int(num1) + int(num2) if request.headers.get('Hx-Request') == 'true': # return only the result to be replaced return render(request, 'blog/post_list_snippet.html', {'num_1': num1,'num_2': num2,'result': result}) else: return render(request, 'blog/post_list.html', {'num_1': num1,'num_2': num2,'result': result}) -
How to declare global variable for all user in Django application?
I want a Queue implementation in my code so all users request is stored in that Queue. I tried implementing request.session['Queue'] but it not working every time its create the new one. My view def fetchVideosContent(request): acc = Account.objects.filter(assgined_to=request.user) tags = request.data['tags'] count = request.data['count'] GenrateLog(log=f'{request.user.username} Staring proccess ') if 'proxyQueue' not in request.session: <--- on every call its enter here GenrateLog(log=f'{request.user.username} Staring Queue') request.session['proxyQueue'] = [] <-- every time new list created else: GenrateLog(log=f'{request.user.username} Addedinf in Queue') <-- not coming here -
how to get data from database using django channels?
I'm trying to practice WebSocket implementation using django channels by querying the database and printing the data but I am unsuccessful. import json from channels.generic.websocket import AsyncWebsocketConsumer from channels.db import database_sync_to_async from .models import Chart from chart.api.serializers import ChartSerializer class ChartConsumer(AsyncWebsocketConsumer): def get_chart(self): return database_sync_to_async(Chart.objects.all)() async def connect(self): data = await self.get_chart() print(data) # <-------- I want to get this data # for i in data: # chart_data = ChartSerializer(i).data # await self.send(json.dumps({'number': chart_data.number})) # print(chart_data) await self.accept() async def disconnect(self, code): pass -
React-router-dom v6 didn't show page when try to route
Hi guys so I'm trying to learn about react-router-dom newest version which is version 6. I tried to create a basic routing in my react-django app, but it didn't work if I create many Routes, for example when i change my route into 8000/product it will show page not found. Can anyone help me with it ? App.js: import React from "react"; import HomePage from "./components/HomePage"; import Product from "./components/Product"; import ProductDetail from "./components/ProductDetail" import { BrowserRouter as Router, Routes, Route, Outlet, } from "react-router-dom"; const App = () => { return ( <> <Router> <Routes> <Route path="/" element={<HomePage/>}/> <Route path="/product" element={<Product/>}/> <Route path="/productdetail" element={<ProductDetail/>}/> </Routes> </Router> <Outlet/> </> ) } export default App -
Use MultipleChoiceField for class
I want to use multipleChoiceField, to choice from model I have model,Template so ,I did this in forms.py class WorkerForm(forms.ModelForm): templates = forms.MultipleChoiceField( Template.objects.all(), required=False, label='template') However it shows error templates = forms.MultipleChoiceField( TypeError: __init__() takes 1 positional argument but 2 were given I am checking the document here. https://docs.djangoproject.com/en/4.0/ref/forms/fields/ However there are only this, not mentioned about using class instance. -
how to create a custom session for log in user in Django
I am trying to login a user by sending a post request to an endpoint, the endpoint is returning status of 200 means the user information is true, but what i have been doing previously in django is simplify using authenticate method and passing user_phone and password later setting that resul to login(request, user_phone), now I dont know what to do here as here I am getting a response from that api which is just a user id, can we do something custom for this result. -
ERROR django.core.exceptions.ImproperlyConfigured:
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Need to return a Single JSON response for two serializers in a customized way
serializers class Consolidated_Final(serializers.ModelSerializer): users = serializers.SerializerMethodField() class Meta: model= Users fields= ['users','id','employee_name','billable_and_non_billable'] def get_users(self,obj): query = Add_Job.objects.all() return Add_Job_Serializers(query, many =True).data views @api_view(['GET']) def final_view(request): q1 = Users.objects.values('id','employee_name','billable_and_non_billable',) query = Consolidated_Final(q1,many=True) return Response(query.data) It is returning me the JSON response as [ { "users": [ { "id": 1, "job_name": "timesheet", "Hours": "12:12:00", "start_Date": "0121-12-12T12:12:00+05:53", "end_Date": "1211-12-12T12:12:00+05:53", "client": 1, "project": 1, "user": 1 }, { "id": 2, "job_name": "Add", "Hours": "12:12:00", "start_Date": "1212-12-12T12:01:00+05:53", "end_Date": "0121-12-12T12:12:00+05:53", "client": 1, "project": 2, "user": 2 } ], "id": 1, "employee_name": "vinoth", "billable_and_non_billable": "Billable" }, { "users": [ { "id": 1, "job_name": "timesheet", "Hours": "12:12:00", "start_Date": "0121-12-12T12:12:00+05:53", "end_Date": "1211-12-12T12:12:00+05:53", "client": 1, "project": 1, "user": 1 }, { "id": 2, "job_name": "Add", "Hours": "12:12:00", "start_Date": "1212-12-12T12:01:00+05:53", "end_Date": "0121-12-12T12:12:00+05:53", "client": 1, "project": 2, "user": 2 } ], "id": 2, "employee_name": "Maari", "billable_and_non_billable": "Billable" }, { "users": [ { "id": 1, "job_name": "timesheet", "Hours": "12:12:00", "start_Date": "0121-12-12T12:12:00+05:53", "end_Date": "1211-12-12T12:12:00+05:53", "client": 1, "project": 1, "user": 1 }, { "id": 2, "job_name": "Add", "Hours": "12:12:00", "start_Date": "1212-12-12T12:01:00+05:53", "end_Date": "0121-12-12T12:12:00+05:53", "client": 1, "project": 2, "user": 2 } ], "id": 3, "employee_name": "Maari", "billable_and_non_billable": "Billable" } ] I need the JSON response as [ { "users": [ { "id": 1, "job_name": "timesheet", "Hours": … -
How to streamline code using for statement when rendering in django's views.py
I'm using django and the code below works inefficiently. Is there a way to shorten the method of creating and appending a list by using a for statement as in the code below? list is used to create graphs in apex chart javascript. [views.py] annotations = {} types = ('A', 'B', 'C', 'D', 'E', 'F') for type in types: annotations[type] = Count('id', filter=Q(type=type)) annotations[f'r_{type}'] = Count('id', filter=Q(type=type, is_recruiting='Recruiting')) annotations[f'N_{type}'] = Count('id', filter=Q(type=type, is_recruiting='Not yet recruiting')) annotations[f'H_{type}'] = Count('id', filter=Q(type=type, is_recruiting='Holding')) annotations[f'C_{type}'] = Count('id', filter=Q(type=type, is_recruiting='Completed')) counts = Research.objects.values('teacher').annotate(**annotations).values('teacher', *annotations.keys()) teacher = []; A = []; B= []; C= []; D= []; E= []; F= []; r_A = []; r_B = []; r_C = []; r_D = []; r_E = []; r_F = []; ... C_E = []; C_F = []; for count in counts: teacher.append(str(count['teacher'])) A.append(str(count['A'])) B.append(str(count['B'])) C.append(str(count['C'])) D.append(str(count['D'])) E.append(str(count['E'])) F.append(str(count['F'])) r_A.append(str(count['r_A'])) r_B.append(str(count['r_B'])) r_C.append(str(count['r_C'])) r_D.append(str(count['r_D'])) r_E.append(str(count['r_E'])) r_F.append(str(count['r_F'])) ... C_E.append(str(count['C_E'])) C_F.append(str(count['C_F'])) return render(request, 'graph.html', { 'teacher': teacher, 'A': A, 'B': B, 'C': C, 'D': D, 'E': E, 'F': F, 'r_A': r_A, 'r_B': r_B, 'r_C': r_C, 'r_D': r_D, 'r_E': r_E, 'r_F': r_F, ... 'C_E': C_E, 'C_F': C_F }) [graph.html] series: [{% if is_recruiting == 'Recruiting' %} { name: 'A', data: {{ r_A … -
Problem installing Django Tech Stack on Apples M1
I just got a new Mac with an M1 chip, but I have problems getting our stack to run. Its a django project, with a few dependencies attached. Most of them being: grpcio google-cloud-vision googlemaps When installing on a fresh M1, using python 3.9.10, i get this error Traceback (most recent call last): File "/Users/tl/work/project/./manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/tl/work/project/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/Users/tl/work/project/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute django.setup() File "/Users/tl/work/project/venv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/tl/work/project/venv/lib/python3.9/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/Users/tl/work/project/image_analysis/apps.py", line 8, in ready import image_analysis.signal_handlers File "/Users/tl/work/project/image_analysis/signal_handlers.py", line 6, in <module> from image_analysis.analyze import analyze_images File "/Users/tl/work/project/image_analysis/analyze.py", line 8, in <module> from google.cloud import vision File "/Users/tl/work/project/venv/lib/python3.9/site-packages/google/cloud/vision/__init__.py", line 18, in <module> from google.cloud.vision_v1.services.image_annotator.async_client import ( File "/Users/tl/work/project/venv/lib/python3.9/site-packages/google/cloud/vision_v1/__init__.py", line 21, in <module> from .services.image_annotator import ImageAnnotatorClient as IacImageAnnotatorClient File "/Users/tl/work/project/venv/lib/python3.9/site-packages/google/cloud/vision_v1/services/image_annotator/__init__.py", line 18, in <module> from .client import ImageAnnotatorClient File "/Users/tl/work/project/venv/lib/python3.9/site-packages/google/cloud/vision_v1/services/image_annotator/client.py", line 27, in <module> from google.api_core import gapic_v1 # type: ignore File "/Users/tl/work/project/venv/lib/python3.9/site-packages/google/api_core/gapic_v1/__init__.py", line 18, in <module> from google.api_core.gapic_v1 import config File "/Users/tl/work/project/venv/lib/python3.9/site-packages/google/api_core/gapic_v1/config.py", line 23, in <module> import grpc File "/Users/tl/work/project/venv/lib/python3.9/site-packages/grpc/__init__.py", line 22, in <module> from grpc import _compression File "/Users/tl/work/project/venv/lib/python3.9/site-packages/grpc/_compression.py", line 15, in <module> from grpc._cython import cygrpc ImportError: … -
How do I get Multiple Select Value from HTML Form in django?
Actually, I am fetching data from API and displaying the data as form to submit in models <label for="images">Images:</label><br> <select name="images" id="images" multiple> {% for img in images %} <option value="{{img}}">{{img.image_name}}</option> {% endfor %} </select> But When I print(request.POST['images']) Returns {'id': 3, 'image_name': 'abc2', 'image': '/media/blogs/Screenshot_from_2022-02-09_12-04-07_P2JqvW7.png'} Returns The last I have selected Can Anyone Plz Help Me Thanks -
How to add select all checkbox in Django admin panel to all editable column?
I searched in the last day for information about how to add a select/deselect all checkbox into my Django admin panel but I didn't find the solution. I like to have these checkbox for all the columns not just for the first (in this case the user model). I like to manage all the objects with one checkbox click but it is also important to save the choice and if I come back to this site it should show the condition I saved before. I attached an image about what I like to do. -
why i am getting this error?can anyone help me...?
user registration using mysql django This is the error im getting and can't find to resolve it.Can anyone help me, i'm using python django and mysql as database with a custom user model...? AttributeError at /accountregister/ 'Manager' object has no attribute 'create_user' Request Method: POST**strong text** Request URL: http://127.0.0.1:8000/accountregister/ Django Version: 3.2.7 Exception Type: AttributeError Exception Value: 'Manager' object has no attribute 'create_user' Exception Location: /home/akshay/Django/mysite/account/views.py, line 20, in register Python Executable: /home/akshay/Django/my_env/bin/python Python Version: 3.8.10 Python Path: ['/home/akshay/Django/mysite', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/akshay/Django/my_env/lib/python3.8/site-packages'] Server time: Wed, 16 Feb 2022 06:38:41 +0000 Traceback Switch to copy-and-paste view /home/akshay/Django/my_env/lib/python3.8/site-packages/django/core/handlers/exception.py, line 47, in inner response = get_response(request) … ▶ Local vars /home/akshay/Django/my_env/lib/python3.8/site-packages/django/core/handlers/base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars /home/akshay/Django/mysite/account/views.py, line 20, in register user=Newuser.objects.create_user(username=username,Email=Email,pwd1=pwd1,pwd2=pwd2,gender=gender) … ▶ Local vars this is my views.py from django.shortcuts import render from django.contrib.auth.models import * from .models import * from django.contrib import messages def index(request): return render(request,'accounts/index.html') def register(request): if request.method == 'POST': username = request.POST['uname'] Email = request.POST['email'] pwd1 = request.POST['pass1'] pwd2 = request.POST['pass2'] gender=request.POST['gend'] user=Newuser.objects.create_user(username=username,Email=Email,pwd1=pwd1,pwd2=pwd2,gender=gender) user.save() messages.success("user saved successfully....!") return render(request,'accounts/register.html') else: return render(request,'accounts/register.html') this is my models.py................... class Newuser(models.Model): username=models.CharField(max_length=50) Email=models.CharField(max_length=50) pwd=models.CharField(max_length=50) gender=models.CharField(max_length=1) this is my urls.py........................ urlpatterns … -
Django admin stackedinline adding new data
I am using stackedInline for Django admin and when trying to add new data the existing data appears below as new tabs how can I solve that. my model category is as follows class Category(models.Model): '''category model for the genere of the stories''' id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=100) owner = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='categories', on_delete=models.CASCADE, null=True, blank=True ) is_primary = models.BooleanField(default=False) parent_category = models.ForeignKey( "self", related_name="children", on_delete=models.SET_NULL, null=True, blank=True, default=None) and my admin is like this class TabedAdmin(admin.StackedInline): model = Category extra = 1 class CategoryAdmin(admin.ModelAdmin): inlines = [TabedAdmin, ] def get_queryset(self, request): queryset = super(CategoryAdmin, self).get_queryset(request) queryset = queryset.filter(is_primary=True).all() # you logic here to `annotate`the queryset with income return queryset and when trying to add new data from the admin the form shows that the first section is empty and all the available categories are listed as like an edit view from the second tab itself. what might be the reason for this? -
Settings.py returning ModuleNotFound error on app that exists
I am relatively new to Django and trying to create a simple app to enable a user to signup and login However when I try to runserver to test what I currently have I run into this error message: ModuleNotFoundError: No module named 'signup.app' This is the structure of my project peerprogrammingplat --- peerprogrammingplat --- signup this is my installed apps in my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'signup.app.SignupConfig', ] my views.py from .models import * def register(response): form = UserCreationForm() return render(response, "signup/register.html", {"form":form}) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('register/', signupv.register, name="register"), ] -
[Django]Intermittent unauthorized API requests when using tokens
I am using tokens for Django rest API authentication. I noticed that in the logs, from time to time, there are unauthorized requests. The user that the token created for is set to be superuser, and other requests are successful, so it shouldn't be the problem of the token/permission. Is there some kind of connection pool limit or anything that would cause such unauthorized problem but then recover quickly? I am using 'rest_framework' and 'rest_framework.authtoken'. REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } -
React/Django cannot update data in a table without also updating the image field associated with it
I am developing a web application project for an alumni group using react/django and using axios to fetch data. Right now, I am able to Create an event with fields such as (event_name, date, images, etc.). I am also able to update the event details, but my problem is that I cannot update any other fields without also changing the picture. I've handled the null requests through django and when I test on Postman and any api views, POST/PUT/DELETE/GET all work fine, so I believe it's something to be handled in react. The image field is labeled gallery. Below is a js file that contains a form that populates the form inputs with the data from for a particular event. Any help would be appreciated. I've tried to look for other answers, but just because they might be out there, doesnt mean I know where to look or how to interperet that is what I'm doing wrong, seeing im just a beginner. import React, { useState, useEffect } from "react"; import { useNavigate, useParams } from "react-router-dom"; import { getEventById, updateEventById } from "../../../api/apiCalls"; const EventUpdate = () => { let navigate = useNavigate(); const { id } = useParams(); … -
Multiple related foreignkeys
class Flow(models.Model): name = models.CharField(max_length=200) pre_requisite = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL) pre_requisite_status = models.ForeignKey("FlowStepStatus", on_delete=models.SET_NULL, null=True, blank=True, related_name='pre_requisite_status') This gives me one pre-requisite and it's status (pre_requisite_status). But I want to have flexibility for multiple pre_requisite and their respective statuses. How can I modify model to have it? -
Make a route expire in a short time
I am trying to implement a task that for rating services. Users will be receiving a SMS text message including a short link. After click that short link, they will fill out the information and submit. And then I will store those information in the database. That is the requirement, now move on to implement part. I am thinking to generate a route like this: https://www.app.com/{customerId}/?access_token=fdsaf.dsaf.fdsafads Then put it under bitly or short.io. The access_token will only valid for 10 seconds start from the time that the url is generated. Do you think is it good enough for safety ? any suggestion would be highly appreciate. Thank you. -
messages.error doesn't work with fetch js in form, Django
views: if request.method == "POST": user_name = request.POST['user_name'] email = request.POST['email'] password = request.POST['password'] re_password = request.POST['re_password'] if len(user_name) >= 16: messages.error(request, 'Too long') ... js: const form = document.forms["register_form"]; const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; form_data = new FormData(form); myHeaders = new Headers() myHeaders.append("X-CSRF-Token", csrftoken) fetch("/account/register/", { headers: myHeaders, body: form_data, method: "POST" }).then(function (response) { if (response.ok) { console.log("successfully registered"); return response.json(); } return Promise.reject(response); }).then(function (data) { console.log(data); }).catch(function (error) { console.warn('Custom Error:', error); }); }) html: <form method="POST" name="register_form" id="register-form"> {% csrf_token %} .... fields .... {% for message in messages %} {{message}} {% endfor %} form working correctly and POST data without reloading page... but problem is about messages.error it doesn't work in template...any problem ? there is any solution to show errors from views in back-end without page refresh ? -
GCC ERROR IN CPanel Terminal Trying to Install Pillow
Please I need help, I am trying to host a Django Project in Cpanel. I have created a Python App (Python 3.8.6) Launched the Virtualenv on Terminal and install django according to my project version (Django 3.2.6) Now Trying to install Dependencies such as Pillow and Mysqlclient, I keep getting the below error. unable to execute '/opt/rh/devtoolset-7/root/usr/bin/gcc': No such file or directory building 'PIL._imagingmorph' extension /opt/rh/devtoolset-7/root/usr/bin/gcc -Wno-unused-result -Wsign-compare -DNDEBUG -D_GNU_SOURCE -fPIC -fwrapv -O2 -fno-semantic-interposition -pthread -Wno-unused-result -Wsign-compare -ffat-lto-objects -flto-partition=none -g -std=c99 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Werror=implicit-function-declaration -D_GNU_SOURCE -fPIC -fwrapv -D_GNU_SOURCE -fPIC -fwrapv -O2 -fno-semantic-interposition -pthread -Wno-unused-result -Wsign-compare -ffat-lto-objects -flto-partition=none -g -std=c99 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Werror=implicit-function-declaration -fPIC -I/usr/include/freetype2 -I/tmp/pip-build-hrzlinrf/pillow -I/home/westhfef/virtualenv/humanities/3.8/include -I/usr/include -I/opt/alt/python38/include/python3.8 -c src/_imagingmorph.c -o build/temp.linux-x86_64-3.8/src/_imagingmorph.o unable to execute '/opt/rh/devtoolset-7/root/usr/bin/gcc': No such file or directory unable to execute '/opt/rh/devtoolset-7/root/usr/bin/gcc': No such file or directory error: command '/opt/rh/devtoolset-7/root/usr/bin/gcc' failed with exit status 1 I have tried everything I can, but didn't work. -
How to reference queryset result in Django
The class model I wrote is complex and large, so I can't write all the code here. Please understand. [views.py] separate_line = Assignment.objects\ .values('id')\ .annotate(ABC=Min(F('feedback__ABC_date')))\ .annotate(C1D1_ABC=ExpressionWrapper(Cast(F('feedback__injection_date'), DateField()), output_field=DateField()) - ExpressionWrapper(Cast(F('ABC'), DateField()), output_field=DateField())) \ .values('id', 'C1D1_ABC') Result: <QuerySet [{'id': 3391, 'C1D1_ABC': datetime.timedelta(days=13)}, {'id': 3392, 'C1D1_ABC': datetime.timedelta(days=27)}]> I succeeded in extracting the desired queryset by creating the C1D1_ABC field using id and annotation. ABC_C1D1 = Feedback.objects.values('assignment__research')\ .annotate(separate_sum=Sum(separate_line['C1D1_ABC'], filter=Q(assignment_id__in=separate_line['id'])), separate_count=Count('assignment', distinct=True, filter=Q(assignment_id__in=separate_line['id'])))\ .values('assignment__research__research_name', 'separate_sum', 'separate_count')\ I am trying to apply the queryset result(-> separate_line) to another ORM calculation, but the following error occurs. Error Message: QuerySet indices must be integers or slices, not str. If I replace ['id'] with [0] referring to the error message, the following error message occurs. Error Message: Field 'id' expected a number but got 'id'.