Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Websockets won't work on docker with nginx
I have a problem with a real-time chat application on Django. The websockets won't work on nginx server. Am I missing something? The app only says: /ws/socket-server/ not found nginx.conf upstream project { server web:8000; } server { listen 80; location / { proxy_pass http://project; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /home/app/web/staticfiles/; } #path to proxy my WebSocket requests location /ws/socket-server/ { proxy_pass http://project; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection “upgrade”; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } asgi.py """ ASGI config for project project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import scrumboard.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AuthMiddlewareStack( URLRouter( scrumboard.routing.websocket_urlpatterns ) ) }) settings.py from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. from django.template.context_processors import media BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ SECRET_KEY = os.environ.get("SECRET_KEY") DEBUG = int(os.environ.get("DEBUG", default=0)) # 'DJANGO_ALLOWED_HOSTS' should be … -
Building wheel for lxml (setup.py): finished with status 'error'
I have this error while running docker Everything works in server but locally lxml finishes with this error: #0 55.92 Stored in directory: /root/.cache/pip/wheels/02/f8/c2/4a8e9dce6caefe8931213e951f7d1b19e6a7d86fc2becc228e #0 55.92 Building wheel for lxml (setup.py): started #0 57.58 Building wheel for lxml (setup.py): finished with status 'error' #0 57.60 error: subprocess-exited-with-error #0 57.60 #0 57.60 × python setup.py bdist_wheel did not run successfully. #0 57.60 │ exit code: 1 #0 57.60 ╰─> [88 lines of output] #0 57.60 Building lxml version 4.6.3. #0 57.60 Building without Cython. #0 57.60 Building against libxml2 2.9.10 and libxslt 1.1.34 #0 57.60 running bdist_wheel #0 57.60 running build #0 57.60 running build_py #0 57.60 creating build #0 57.60 creating build/lib.linux-x86_64-cpython-311 #0 57.60 creating build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/sax.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/doctestcompare.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/pyclasslookup.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/ElementInclude.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/cssselect.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/_elementpath.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/builder.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/usedoctest.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/__init__.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 creating build/lib.linux-x86_64-cpython-311/lxml/includes #0 57.60 copying src/lxml/includes/__init__.py -> build/lib.linux-x86_64-cpython-311/lxml/includes #0 57.60 creating build/lib.linux-x86_64-cpython-311/lxml/html #0 57.60 copying src/lxml/html/_setmixin.py -> build/lib.linux-x86_64-cpython-311/lxml/html #0 57.60 copying src/lxml/html/_diffcommand.py -> build/lib.linux-x86_64-cpython-311/lxml/html #0 57.60 copying src/lxml/html/diff.py … -
get the id of a related field and save data
I'm kinda new to DRF, I am building a database for attendance. I want to save an instance of AttendanceSlot in my Attendance but I don't know how to get id, so i can save it... models.py class AttendanceSlot(models.Model): department_id = models.ForeignKey("students.Department", verbose_name=_("department id"), on_delete=models.CASCADE) course_id = models.ForeignKey("students.Course", verbose_name=_("course id"), related_name= 'course', on_delete=models.CASCADE) lecturer_id = models.ForeignKey("lecturers.Lecturer", on_delete=models.CASCADE) date = models.DateField(_("attendance date"), auto_now=False, auto_now_add=True) start_time = models.TimeField(_("start time"), auto_now=False, auto_now_add=False) end_time = models.TimeField(auto_now=False, auto_now_add=False) longitude = models.CharField(_("longitude"), max_length=50) latitude = models.CharField(_("latitude"), max_length=50) radius = models.CharField(_("radius"), max_length=50) def __str__(self): return '{0}'.format(self.course_id.course_code) class Attendance(models.Model): slot_id = models.ForeignKey("attendance.AttendanceSlot", verbose_name=_("attendance slot"), on_delete=models.CASCADE) student_id = models.ForeignKey("students.Student", on_delete=models.CASCADE) performance = models.CharField(max_length=50) serializers.py class AttendanceSerializer(serializers.ModelSerializer): # student_id = serializers.SlugField(read_only=True) slot_id = serializers.PrimaryKeyRelatedField(queryset=AttendanceSlot.objects.all(), many=False) class Meta: model = Attendance fields = ['student_id', 'slot_id', 'performance'] views.py class Attendance(ListCreateAPIView): queryset = Attendance.objects.all() serializer_class = AttendanceSerializer def get_queryset(self, *args, **kwargs): id = self.kwargs['pk'] slot = AttendanceSlot.objects.get(id=id) return slot def perform_create(self, serializer): serializer.save(user = self.request.user, slot_id=self.get_queryset()) return super().perform_create(serializer) urls.py path('<int:pk>/', views.Attendance.as_view(), name='attendance'), -
Django - Storing user info sessions vs database
In my django website I have a login system which uses sessions to keep the user logged in across all pages. I would like to store recently viewed items for users if they are logged in or browsing as a guest user. When a user is logged in I would like the user to see their recently viewed items even when they access my website on another device. I understand that if a user is browsing as a guest recently viewed items would be stored locally in the browser. Would i need to store recently viewed items in a database so that it can be accessed and displayed on other devices. Or is there a way to achieve this with the use of sessions. example of request.session dict { "user_id":-1, # (-1), flag value when no user is logged in (browsing as guest) "recently-viewed":['sw0001a','sw0036a',...], "login_attempts":2, } -
serve Static Files and Media Files of Django app in Production using NGINX
The project works correctly, but I get a 404 error when reading static files! my settings.py: STATIC_URL = 'static/' STATIC_ROOT = '/home/static' MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') nginx.conf: user www-data; worker_processes 1; error_log /var/log/nginx/error.log; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; access_log /var/log/nginx/access.log; upstream main { server 127.0.0.1:8000; } server { listen 80; server_name localhost; charset utf-8; location /static/ { alias /home/static; } location / { proxy_pass http://main; } } } I`m not using gunicorn. are my settings wrong? -
I have a django website hosted on heroku so I want to setup site to site vpn connection between fortgate vpn. My site and another site. How?
I have a djano app hosted on heroku an I want it to exchange data with another site that is using Fortigate vpn. So I am required to setup my vpn connection to my site but heroku's private space and shiel are to expensive for me. Please help. I could find any vpn that is easy to configure its all complex. -
Django - Disable editing via view button
I am making a customer portal on django and on the admin panel i have created a list for all the users in the database. Apart from that i have also added 3 buttons in my table to View, Edit and Delete as shown: Now the problem is that when i click edit or delete button the code runs as it is intended to do. But when i click the view button it still allows the person to modify the details. I only want to use it as read-only. Can someone please help? This is my admin.py from django.contrib import admin from .models import Customer from .forms import CustomerForm from django.http import HttpResponse from django.utils.html import format_html # Write your models here class CustomerAdmin(admin.ModelAdmin): form=CustomerForm list_display = ['id','first_name','last_name','profile_picture', 'gender', 'date_of_birth', 'email', 'phone_number', 'address', 'marry_status','country','state','city','view_button', 'edit_button', 'delete_button'] list_display_links = ['id'] ordering = ('id',) def view_button(self, obj): return format_html('<a class="button" style="background-color: darkgreen;" " href="/admin/customer_form/customer/{}/">View</a>'.format(obj.id)) view_button.allow_tags = True view_button.short_description = 'View' def edit_button(self, obj): return format_html ('<a class="button" style="color: black; background-color: yellow;" href="/admin/customer_form/customer/{}/change/">Edit</a>'.format(obj.id)) edit_button.allow_tags = True edit_button.short_description = 'Edit' def delete_button(self, obj): return format_html('<a class="button" style="background-color: #ba2121;" href="/admin/customer_form/customer/{}/delete/">Delete</a>'.format(obj.id)) delete_button.allow_tags = True delete_button.short_description = 'Delete' admin.site.register(Customer, CustomerAdmin) -
No reverse match at /create Reverse for 'employees-list' not found. 'employees-list' is not a valid view function or pattern name
Reverse for 'employees-list' not found. 'employees-list' is not a valid view function or pattern name. im getting the error like this what can i do plz any one resolve thisenter image description here getting like want to redirect to the employees-list ... -
User object has no attribute 'code', when code is not passed to User.objects.create
Im using Django Rest Framework to create a view that verifies an otp. Currently, it works just fine. models.py class User(AbstractUser): phone_number = PhoneNumberField(blank=True) def __str__(self) -> str: return f"{self.username}" views.py class VerifyOTPCode(APIView): permission_classes=[AllowAny] def post(self, request): serializer = UserOTPCodeSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() return Response(serializer.validated_data, status=status.HTTP_201_CREATED) return Response(serializer.errors) serializers.py class UserOTPCodeSerializer(serializers.ModelSerializer): code = serializers.IntegerField() class Meta: model = User fields = ("first_name", "last_name", "email", "phone_number", "code") def validate(self, data): code, phone_number = str(data['code']), data['phone_number'] if is_six_digits(code) and is_otp_approved(code, phone_number): return data raise serializers.ValidationError('Code was not approved') def create(self, validated_data): del validated_data['code'] return User.objects.create(**validated_data) However, I want to use a generic for the view instead, so I tried refactoring it into the following views.py class VerifyOTPCode(generics.CreateAPIView): permission_classes= [AllowAny] serializer_class= UserOTPCodeSerializer Now, when I try to hit the endpoint, I get an error at create, that the User object has no attribute code, even though create removes code from validated_data, and another thing is that even with the error, a User object still does get created. Why is this error occurring and how can I fix it? Internal Server Error: /user/register/verify-otp/ Traceback (most recent call last): File "C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\fields.py", line 457, in get_attribute return get_attribute(instance, self.source_attrs) File "C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\fields.py", line 97, in … -
django rest framework serializer raising invalid errors
class AdvanceSearchSerializer(serializers.Serializer): all_of_these_words = serializers.CharField(allow_null=True, required=False) this_exact_phase = serializers.CharField(allow_null=True, required=False) any_of_these_words = serializers.CharField(allow_null=True, required=False) class myclass(viewsets.Viewsets): serializer = AdvanceSearchSerializer(data = request.data) it works fine. for now im passing data from post request in postman as form-data but when I change it to raw and wih json format it raising the below errors. show that this field is required even though i have set it to null true. { "response": false, "return_code": "field_error", "result": [], "message": { "all_of_these_words": [ "This field may not be blank." ], "this_exact_phase": [ "This field may not be blank." ], "any_of_these_words": [ "This field may not be blank." ] } } -
How to update dynamic form fields in Django
The users can dynamically add more fields and edit fields to the forms. The problem is I don't know how exactly I should pass the dynamic multiple dynamic 'city' ids and edit-update them. Models.py class Cities(models.Model): cityname = models.CharField(max_length=5000, null = True, blank = True) owner = models.ForeignKey(User, null = True, on_delete=models.CASCADE) relcountry = models.ForeignKey(Country, null = True, on_delete=models.CASCADE) Index.html <form method = "post" action='cityupdate/{{city.id}}' enctype="multipart/form-data"> {% csrf_token %} {% for city in cities %} <input type="text" name = "{{city.id}}" value= "{{city.name}}" </input> {% endfor %} <input type="submit" name = "cityupdate" value= "Update" </input></a> </form> Urls.py path('cityupdate/<str:id>',views.cityupdate,name='pk') Views.py def cityupdate(request,pk): if request.method == 'POST' and 'cityupdate' in request.POST: ----------------- I need help to complete the views.py code -
How can I send Boolean fields via Django send_mail
I am fairly new to Python and Django, I am trying to use the build in send_mail and having a few issues with the boolean fields I want to be included in the email that is sent, I have had no issues with the form being printed to the terminal for testing but as soon as I added the other fields that are on the form(b oolean fields) I am getting the following error (TypeError: sequence item 4: expected str instance, bool found), probably an easy fix but I am struggling to find anything on the web that will help. I am not fussed is the boolean fields that are False are excluded on the email as this is not relevant, any help would be much appreciated. I have managed to get the email side working when it comes to Firstname, Lastname, Email, Phone, but when adding the boolean fields I am getting an error. Views.py from django.shortcuts import render, redirect from django.http import JsonResponse from main.models import WFHSHEET from django.http import HttpResponse, response, HttpResponseRedirect from .forms import WFHLIST, RETURNLIST from django.core.mail import send_mail, BadHeaderError def home(response): return render(response, 'home.html', {}) def wfhsheet(request): if request.method == 'POST': form = WFHLIST(request.POST) … -
Can't show specific model field in my HTML template
On my main page i want to show a category just like {{ post.body }} but instead {{ post.body }} would be {{ post.category }} here. {% extends "base.html" %} {% block title %}Articles{% endblock title %} {% block content %} {% for post in post_list %} <div class="card"> <div class="card-header"> <span class="font-weight-bold"><a href="{% url 'post_detail' post.pk %}">{{ post.title }}</a> | </span> &middot; <span class="text-muted">by {{ post.author }} | {{ post.created_at }}</span> </div> <div class="card-body"> <!-- Changes start here! --> <p>{{ post.body }}</p> <p>{{ post.category }}</p> <a href="{% url 'post_edit' post.pk %}">Edit</a> | <a href="{% url 'post_delete' post.pk %}">Delete</a> | <a href="{% url 'category_list' %}">Category</a> </div> <div class="card-footer"> {% for comment in post.comment_set.all %} <p> <span class="font-weight-bold"> {{ comment.author }} &middot; </span> {{ comment }} </p> {% endfor %} </div> <!-- Changes end here! --> </div> <br /> {% endfor %} {% endblock content %} but cannot to figure out how. But cannot figure out how. Here is my models from django.conf import settings from django.db import models from django.urls import reverse class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return (self.name) def get_absolute_url(self): return reverse("home") class Post(models.Model): title = models.CharField(max_length=255) body = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) created_at = models.DateTimeField(auto_now_add=True) … -
I can't get Django custom error pages to work
I am trying to get custom error pages (404 & 500) to work in my Django application. So far I have the following: urls.py handler404 = views.error_404 handle500 = views.error_500 views.py def error_500(request, exception): return render(request, '500.html', status=500) def error_404(request, exception): return render(request, '404.html', status=404) DEBUG is set to FALSE. However when I try access an error page I get the following error: "A server error occurred. Please contact the administrator." Which (obviously) is not my error template. Any help appreciated! -
Django localisation, internationalization
How to add different language buttons so that it translate my django website online? Or any other method? I want to translate my whole website. In easy way -
I hosted a django website on namecheap but it has changed structure
I have hosted a django business directory system on namecheap but the home page has changed. That's my localhost display of the front end [This is the display of app on thena.thenadaka.com][2] I checked the console to see if there's any static file that is not served but all are served. I know am supposed to learn Docker to ease this but for now your help with be paramount. The code for both is exactly the same, i also disabled Cache under Network on localhost so the locally hosted site doesn'd display cached data -
Django API rejects file
I'm trying to send a csv file to my Django API and response with process data, but when I send it, I get the error: django.utils.datastructures.MultiValueDictKeyError: 'file' this is my react code: import { useState } from 'react'; import './App.css'; function App() { const [file, setFile] = useState(null); const uploadFiles = e =>{ setFile(e); } const insertFile = async() => { const f = new FormData(); f.append("file", file); await fetch( 'http://localhost:8000/api/', { method: 'POST', headers: { 'content-type': 'multipart/form-data' }, body: f, }) .then((response) => response.json()) .then((data)=>{ console.log(data); }) .catch(error=>{ console.log(error); }); } return ( <> <input type="file" name="file" onChange={(e)=>uploadFiles(e.target.files)}/> <button onClick={()=>insertFile()}>Insertar</button> </> ); } export default App; And this is my view.py file that will process the information, for now, I just want to get the csv info in the frontend side, so the logic of how to process data doesn't matter right now. @api_view(['POST']) def eda(request): file = request.FILES['file'] data = [] with open(file, encoding='utf-8') as csvf: csvReader = csv.DictReader(csvf) for rows in csvReader: data.append(rows) response = { 'csvData': data } return Response(response) -
Get a Foreign Key value with django-rest-framework serializers
I'm using the django rest framework to create an API. models.py class DepartmentModel(models.Model): DeptID = models.AutoField(primary_key=True) DeptName = models.CharField(max_length=100) def __str__(self): return self.DeptName class Meta: verbose_name = 'Department Table' class EmployeeModel(models.Model): Level_Types = ( ('Genin', 'Genin'), ('Chunin', 'Chunin'), ('Jonin', 'Jonin'), ) EmpID = models.AutoField(primary_key=True) EmpName = models.CharField(max_length=100) Email = models.CharField(max_length=100,null=True) EmpLevel = models.CharField(max_length=20, default="Genin", choices=Level_Types) EmpPosition = models.ForeignKey(DepartmentModel, null=True, on_delete=models.SET_NULL) class Meta: verbose_name = 'EmployeeTable' # Easy readable tablename - verbose_name def __str__(self): return self.EmpName serializer.py from appemployee.models import EmployeeModel,DepartmentModel class EmployeeSerialize(serializers.ModelSerializer): class Meta: model = EmployeeModel fields = '__all__' class EmployeeSerializer(serializers.ModelSerializer): emp_dept = serializers.CharField(source='DepartmentModel.DeptName') class Meta: model = EmployeeModel fields = ('EmpID','EmpName','Email','EmpLevel','emp_dept') views.py class EmployeeTable(APIView): def get(self,request): try: emp_obj = EmployeeModel.objects.all() empserializer = EmployeeSerialize(emp_obj,many=True) except Exception as err: return Response(err) return Response(empserializer.data) this would provide me with: [ { "EmpID": 1, "EmpName": "Hashirama Senju", "Email": "hashirama.senju@konaha.com", "EmpLevel": "Jonin", "EmpPosition": 1 }, { "EmpID": 2, "EmpName": "Tobirama Senju", "Email": "tobirama.senju@konaha.com", "EmpLevel": "Jonin", "EmpPosition": 2 }, { "EmpID": 3, "EmpName": "Hiruzen Sarutobi", "Email": "hiruzen.sarutobi@konaha.com", "EmpLevel": "Jonin", "EmpPosition": 5 } ] what i really want is [ { "EmpID": 1, "EmpName": "Hashirama Senju", "Email": "hashirama.senju@konaha.com", "EmpLevel": "Jonin", "DeptName": "Hokage" }, { "EmpID": 2, "EmpName": "Tobirama Senju", "Email": "tobirama.senju@konaha.com", "EmpLevel": "Jonin", "DeptName": "Hokage" … -
any docs abot django + htmx for JSON
I found many reference (docs and video) about how to use htmx in django for doing parent-child crud UI. Is there any docs or excample on how to do 'dynamicaly added form field' with just single model class? My case is to make an app that take care of business mailing templates. models.py class MailTemplate(models.Model): code = models.CharField(verbose_name='Code',max_length=10, unique=True) name = models.CharField(verbose_name='Name', max_length=30) docx = models.FileField(verbose_name='docx File') dataschema = models.TextField(null=True, blank=True) class Mail(models.Model): mailtemplate = models.ForeignKey(MailTemplate, on_delete=models.SET_NULL) created = models.DateTimeField(auto_now_add=True) edited = models.DateTimeField(auto_now=True) data = models.TextField(null=True, blank=True) What I want is a form to add/edit record of 'MailTemplate'. that form will 'look like' 'stacked inline' but the 'child' is from parsing MailTemplate.dataschema. Example of MailTemplate.dataschema : [ { "name": "to", "label": "To", "type": "string", }, { "name": "platenumber", "label": "Plate Number", "type": "string", }, ] I really appreciate any help. Sincerely -bino- -
How do I use django templates to get a field from the parent object of a model?
I'm trying to create an interface where students can match with other students in the class for a group project based on shared interests and I have a queryset in a django view and from there I am able to use select_related to get the parent object and even print the fields in Anaconda Prompt (when running on local server) but I can't seem to get the field to show up in a template...what am I missing? Here is the relevant part of my models file: class Profile(models.Model): first_nm = models.CharField(max_length=100) last_nm = models.CharField(max_length=100) class Potential(models.Model): user1 = models.ForeignKey(Profile, related_name='user1', on_delete=models.CASCADE) user2 = models.ForeignKey(Profile, related_name='user2', on_delete=models.CASCADE) Here is the relevant part of my view: def matches(request): my_user = request.user my_id = Profile.objects.get(slug=my_user) the_matches = Potential.objects.filter(Q(user1=my_id) | Q(user2=my_id)).all().select_related('user1','user2') print(the_matches.values()) print(the_matches.values('user2__first_nm')) return render(request,'projects/matches_list.html', { 'matches':the_matches}) Here is the relevant part of the template: {% for match in matches %} <div class="matches"> <p>{{ match.user1__first_nm }}</p> <p>{{ match.user2__first_nm }}</p> </div> {% endfor %} In the template above, why does this not work? Thanks in advance! I have tried using the syntax above like: <p>{{ match.user2__first_nm }}</p> and when just printing to the console I get <QuerySet [{'user2__first_nm': 'test_nm'}]> from the second to last line … -
Uncaught (in promise) Error: Invalid hook call on fetch()
I'm working on a webapp for Django. It is a simple blog. The front end is being built in react and materials UI, it is based off of the tutorial here, but I have had to adapt much by myself because he is using a Class-oriented approach many methods of which are deprecated as React seems to be moving towards a function based model. In the model that the demonstrator created, we are passing data from our react frontend to our django backend by use of generating JSON objects which python serializes. I have built a blog post submission form that doesn't work for a reason I can't understand. CreateBlogPost.js import React, { Component } from "react"; import Grid from "@mui/material/Grid"; import { FormControl, FormHelperText, TextField, Typography, Button } from "@mui/material"; import { Link } from "react-router-dom"; import { useState } from "react"; import { Navigate } from "react-router-dom"; export default function CreateBlogPost(props) { const[title,setTitle] = useState(''); const[content,setContent] = useState(''); const[tags, setTags] = useState(''); const handleTitle = event => { setTitle(event.target.value); } const handleContent = event => { setContent(event.target.value); } const handleTags = event => { setTags(event.target.value); } const requestOptions = { method: "POST", headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ title: … -
Django queryset - fetching reverse relations
I have two models with a one-to-many relation through a ForeignKey. At some stage, I have obtained a queryset of the 'one' objects and would like to retrieve, as efficiently as possible, all of the 'many' objects that are associated with them. Here is a minimal example: class Car(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=1000) @classmethod def search(keyword): return keyword_search_cars(keyword) class Passenger(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE) Now I would like to query the models like so: # Get all passengers in cars matching term 'truck' cars = Car.search('truck') passengers = cars.passenger_set.all() # Not permitted on querysets! But the best I can come up with is something like this: car_ids = Car.search('truck').values_list('id', flat=True) passengers = Passenger.objects.filter(car_id__in=car_ids) With hundreds of records in the cars queryset, the __in filter seems like a dumb way to query the database. According to the docs, this does not do a SQL JOIN but instead writes a huge WHERE id IN (1, 2, 3, ... ) which does not seem optimal. Does anyone know of a better approach for this? Currently my queries take 10+ seconds (with 1M+ records) which means rather poor performance for my application. It will get even slower as the database table grows … -
MultipleObjectsReturned at /vehicle/vehicle_view/ get() returned more than one Vehicle -- it returned 7
`Hello I have more then 1 vehicle in my client side when i was send request from froentend, it return error View.py File @login_required def vehicle_view(request): vehicle = get_object_or_404(Vehicle, user=request.user) form = UpdateVehicleForm(request.POST or None, request.FILES or None,instance=vehicle) context = {'form': form } if request.method == 'POST': if form.is_valid(): vehicle.save() messages.success(request, "Vehicle Updated!") return redirect('home') else: messages.error(request, "Invalid Data Provided") return render(request, "user/edit_vehicle.html", context) urls.py path('vehicle_view/',views.vehicle_view,name='vehicle_view'), ` -
I have an ecommerce website of multiple selllers
I want following solution: Client need a shipping API for domestic and international locations on the basis of multiple sellers cost and also client need all activities of shipping api done in their own website. Please Provie me the best and cheap solution according to this situation. -
Can't make jquery toggle function top show a comment form for posts lists, It opens only the first one [duplicate]
I'm working on a blog app to hone my django skills. I'm trying to create a posts list page with a quick one field comment form for each post, kind of like you will see on facebook, or linkedin. I'm decided to use jquery for this, and it only opens/toggles the first post. How do I pass a unique user or user id with jinja to jquery? Is that how you do it? Can someone please guide me to the right path to accomplish this? {% extends 'posts/base.html' %} {% block content %} <style type="text/css"> .card{ margin-bottom: 20px; } </style> <div class="container"> <div class="row"> <div class="col-md-2">left</div> <div class="col-md-8"> {% for post in posts %} <div class="card"> <div class="card_header"> <a href="{{post.get_absolute_url}}">{{post.title}}</a> </div> <div class="card_meta_header"> ... </div> <div class="card_featured_image"> <img src="{{post.featured_image.url}}" class="img-fluid"> </div> <div class="card_text"> <p>{{post.content_short|safe}}</p> </div> <div id="commenting" style="display:none;"> <label for="inputPassword5" class="form-label">Password</label> <input type="password" id="inputPassword5" class="form-control" aria-describedby="passwordHelpBlock"> </div> <script type="text/javascript"> $(document).ready(function(){ $("#openFormPanel").click(function(){ $("#commenting").toggle(); }); }); </script> <div class="card_footer"> ... </div> <button id="openFormPanel" >Open form panel to leave comment</button> </div> {% endfor %} </div> <div class="col-md-2">right</div> </div> </div> {% endblock %} {% include 'posts/footer.html' %}