Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO | How to update relation nested without validate each foreign key
How to update relation nested without validate each foreign key. Is there a way to avoid validating each foreign key inside a relation list? { "name": "Item 0037", "price": 10, "category":2, "prices_list": [ { "id": 192, "price_list_id": 1, "price": 999.97 }, { "price_list_id": 2, "price": 888.99 }, { "price_list_id": 2, "price": 234.99 } ] } I'm using django-rest-framework (serializers, viewset), but every time I send the data I see that it does a validation for each relationship, is there something similar to fetch_related that only does a query? -
Why don't I have a button in django rest framework for dynamically adding nested form data, if there should be one?
I ask for help Take a look at the screenshot please, I can't understand why I can't add links dynamically Click 1 This is the kind of Json format data you should get: values { "firstname": "l", "lastname": "m", "links": [ { "linkname": "https://www.youtube.com/", "linkurl": "https://www.youtube.com/" }, { "linkname": "https://www.youtube.com/", "linkurl": "https://www.youtube.com/" } ] } And besides, even if all these existing fields are filled in (well, that is, those fields that are already in the django rest framework, namely, one array of links and the First Name along with the Last Name), an error is displayed: The .create() method does not support writable nested fields by default. Write an explicit .create() method for serializer schedule.serializers.WorkSuperSerializer, or set read_only=True on nested serializer fields. I went through a lot of solutions to the problem, for example, I declared the create() method: def create(self, validated_data): links_data = validated_data.pop('links') worksuper = WorkSuper.objects.create(**validated_data) for link_data in links_data: Link.objects.create(worksuper=worksuper, **link_data) return worksuper But it didn't fix the error((((( In general, here is my code: Models.py: class WorkSuper(models.Model): firstname = models.CharField("Имя", max_length=10, blank=True) lastname = models.CharField("Фамилия", max_length=30, blank=True) class Link(models.Model): links = models.ForeignKey(WorkSuper, related_name='links', on_delete=models.CASCADE, blank=True) linkname = models.CharField("linkname", max_length=100, blank=True) linkurl = models.CharField("linkurl", max_length=100, blank=True) … -
In the app engine dashbord, requests from uri are displayed that I don't know the origin, does anyone know where it comes from?
Dashboard do App engine A friend told me that it looks like wordpres was downloaded along with the app because they are common wordpress uris, but he's not sure. I thought that they were due to Google Cloud services (App engine, Storage, Logging, Build, Secret manager) but I'm not sure either? Is it one of those cases? Is it a problem and if so is there a fix? Obs: I don't know it it helps, but the site is develop with django, boostrap and jquery. I even write in browser the uri but nothing that i wouldn't expect appear. I don't even know how to work with wordpress. -
Annotation by condition
I have 2 models: class City(models.Model): title = models.CharField() class VisitedCity(models.Model): city = models.ForeignKey(City) user = models.ForeignKey(User) I want to make a queryset with annotated fields visited boolean type: if this city in visitedcity model and user=self.request.user => True if not => False `City.objects.annotate( ... something ... )` I tried to use annotate() like this one, but it is not work: queryset_visited = VisitedCity.objects.filter(user=self.request.user) queryset_all = City.objects.annotate( visited=Case( When(title__in=queryset_visited, then=Value(True)), default=Value(False) ) ) Could you please help me with this question? -
NPM error in Django application deployment in Render
I’m trying to deploy a Django application in Render. My operating system is Windows. I use tailwind and when it is executed in the Render virtual machine the command 'python manage.py tailwind build' appears the following error of npm: sh: 1: rimraf: not found npm ERR! code ELIFECYCLE npm ERR! syscall spawn npm ERR! file sh npm ERR! errno ENOENT npm ERR! theme@3.4.0 build:clean: `rimraf ../static/css/dist` npm ERR! spawn ENOENT npm ERR! npm ERR! Failed at the theme@3.4.0 build:clean script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. I have in the requirements.txt nodejs==0.1.1 and npm==0.1.1. And in the settings.py: NPM_BIN_PATH = "/usr/bin/npm". Below I show the build.sh file: set -o errexit pip install -r requirements.txt python manage.py collectstatic --no-input python manage.py migrate python manage.py tailwind build if [[ $CREATE_SUPERUSER ]]; then python manage.py createsuperuser --no-input fi -
Custom "per-tenant" views in Django
I developed a multi-tenant Django app (single DB with single schema and domain-based, eg. https://tenant-xyz.esample.com) and I'd like to be able to customize some views according to the current tenant. For example, /my_app/some_view might include some logic while /my_app/tenant_xyz/some_view might behave in a different way. Of course I could also have /my_app/tenant_abcdef/some_unique_view_for_tenant_abcdef_only. Following Django's urls.py phylosophy, I guess custom views could be enclosed in their own views_tenant_xyz.py and tenant-related URLs would point to custom views files. The simplest intuition was to to dynamcally include tenants' custom views URLs in urls.py (without typing them statically). Given a urls.py fragment: urlpatterns = [ path('', include('my_app.urls')), path('admin/', admin.site.urls), ] I thougth I could include the following code in urls.py: for tenant in Tenant.objects.all(): urlpatterns += [ path(f'custom_views/{tenant.name}/', include(f'myapp.tenants.urls_{tenant.name}', namespace=f'customviews{tenant.name}')), ] and then define custom CVB (or functions) in each myapp.tenants.urls_{tenant.name}.py but I get an "SynchronousOnlyOperation at / You cannot call this from an async context - use a thread or sync_to_async." (I'm running ASGI with Gunicorn + Uvicorn workers). Btw I suppose using ORM inside settings.py is not the best approach. What would you advise me to do? Keep in mind that each tenant.name is a sort of slug. Thanks in advance. -
the error when I click on the link of the read more button to display a post in detail : Server Error TypeError: fetch failed
`Server Error TypeError: fetch failed export const getAllPosts = async () => { const response = await fetch('http://localhost:8000/blog/posts/'); ^ const posts = await response.json(); return posts; };` honestly i don't understand this error Why this error here, when this getAllPosts works well and it is what allows me to display all the posts on the blog page before I click to see in detail. there should be no error at this level at least if I couldn't display all the posts, I will know and understand that this fetch is not working. I don't know if you see where I'm coming from? -
how can i make sort divs in a certain way
I'm making a todo app with django and every todo has a bootstrap card with todo items in a list but when I add todos they keep squeezing next to each other so how can I make it that when there are 3 divs in a row it makes a new row for the rest of the divs I tried searching the internet and stack overflow but found nothing -
Http 413 Request entity too large error only in Safari browser
I have a Django app being served by Nginx. When I upload an image via AJAX with PATCH method to my app I get that error. The thing is that I don't get that error on Chrome or Firefox. I only get in Safari. Doesn't matter if it's Mac or iPhone. The photo is 3.5mb. On Nginx conf I have client_max_body_size 50M; On Django I have DATA_UPLOAD_MAX_MEMORY_SIZE = 50*1024*1024 When I inspect the request on those 3 browsers i see this: Firefox: content-length 355705 Chrome: content-length 355669 Safari: content-length 4815964 What it could be? Any ideas? I tried to upload an image with 3 different browsers, but I failed in one of them -
How do I create a serializer for this category model without the product field? DRF
I want to create a Apiview for the model category and define an endpoint for only perform a create category fields but Products and Category are related for ForeignKey method. So, I was trying this method but any works yet. these are my models: class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(blank=True) class Meta: ordering = ('name',) def __str__(self): return self.name def get_absolute_url(self): return f'/{self.slug}/' class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) # Cascade deletes. Django emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey. name = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(blank=True, null=True) price = models.DecimalField(max_digits=15, decimal_places=2, default=99.99) image = models.ImageField(upload_to='uploads/', blank=True) thumbnail = models.ImageField(upload_to='uploads/', blank=True) date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-date_added',) # date create it in descending order def __str__(self): return self.name I create a serializer for products models and for category, work only for create products. class ProductSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='product-detail', lookup_field='pk' ) class Meta: model = Product fields = ( "category", "url", "pk", "name", "description", "price", "get_image", "get_thumbnail", "date_added", ) class CategorySerializer(serializers.ModelSerializer): products = ProductSerializer(many=True) class Meta: model = Category fields = ( "id", "name", "get_absolute_url", "products", ) also I was trying this … -
Django: Prefetch on through table with filter
I have the following models: class Person(models.Model): name = models.CharField(max_length=255) class Group(models.Model): name = models.CharField(max_length=255) members = models.ManyToManyField( Person, through="Membership", ) class Membership(models.Model): group = models.ForeignKey( Group, on_delete=models.CASCADE, related_name="membership", ) person = models.ForeignKey( Person, on_delete=models.CASCADE, related_name="membership", ) is_active = models.BooleanField( null=True, blank=True ) The is_active on membership denotes whether a person is still a part of the group. I am trying to query groups and prefetch all active members. The script that I am using is from sample.models import Person, Group from django.db.models import Prefetch from django.db import connection, reset_queries reset_queries() qs = Group.objects.prefetch_related( Prefetch( "members", queryset=Person.objects.filter( membership__is_active=True, ), ) ) print(list(qs.all())) print(len(connection.queries)) # Should be two queries print(connection.queries[-2].values()) print(connection.queries[-1].values()) However, the query that gets generated for the prefetch is SELECT ("sample_membership"."group_id") AS "_prefetch_related_val_group_id", "sample_person"."id", "sample_person"."name" FROM "sample_person" INNER JOIN "sample_membership" ON ( "sample_person"."id" = "sample_membership"."person_id" ) INNER JOIN "sample_membership" T3 ON ( "sample_person"."id" = T3."person_id" ) WHERE ( "sample_membership"."is_active" AND T3."group_id" IN (1, 2) ) There are two joins on sample_membership and only one of them has the is_active filter. (This is an abstracted version of what I am trying to solve - but the essence remains the same - having the ability to add filters on the m2m … -
Django Login/authenticate user not sticking around
I've been trying to implement a simple login/logout/signup system for my Django project, but the login doesn't seem to have any effect or stick around when the user change pages (in other words, request.user.is_authenticated is False if I go from the login page to the user, home or credit page or any other page). I have another project with a similar code and it works, so I'm really lost. The Authenticate doesn't work either, so I have a manual one. Views.py def userCreate(request): """ Creating a new user """ user=User() user_form = UserForm(request.POST or None, instance=user) if user_form.is_valid(): user_form.save() if user is not None: login(request, user) return redirect('user_home', user_id=user.id) return render(request, 'lognom/user_create.html', {'user_form':user_form}) def userLogIn(request): LogInForm_form = LogInForm(request.POST or None) if LogInForm_form.is_valid(): email_field = LogInForm_form.cleaned_data['login_email'] password_field = LogInForm_form.cleaned_data['login_password'] try: user=User.objects.get(user_email=email_field) except: error="Invalid user email or password" return render(request, 'lognom/login.html', {'LogInForm_form':LogInForm_form, 'error':error}) if user.password == password_field: if user is not None: login(request, user) return redirect('user_home', user_id=user.id) else: error="Invalid user email or password" return render(request, 'lognom/login.html', {'LogInForm_form':LogInForm_form, 'error':error}) return render(request, 'lognom/login.html', {'LogInForm_form':LogInForm_form}) def userLogOut(request): """ Log out """ logout(request) return render(request, 'lognom/logout.html') models.py class User(AbstractBaseUser): ''' This table is the User table. Signing up/in uses email and password. ''' ## This field … -
Setting up separate database for django apps
I am working on a project. I want the client to populate the apps I've worked on with real data while I'm working on the remaining part of the project. But right now I'm confused on how to go about it. I'm thinking on setting up separate database for each app but I'm a novice in web development, so I don't know if it is a good idea. I'll also like to get a sample implementation for setting up separate database tables in Django. or if there a better alternative way to do I'll be grateful to know. -
How can I update my profile from HTML form template in Django?
I am fairly new to Django and I use Django 4.2. I am having a bit of an issue with updating the info of an already saved user on the edit profile page. This is the form in the HTML template: {% block content %} <main class=" mb-[200px] z-0 main max-sm:mt-0 "> <hr class="border-t-1 border-t-black"> <div class="my-5 py-3"></div> <div class="my-5 py-3"></div> <section class="width p-4 bg-white"> <div class="form-c shadow-md bg-[#bba58f]"> <form action="" method="post" class="form-control" enctype="multipart/form-data"> {% csrf_token %} <div class="w-[350px] inline-block shadow-md"> <h4 class="h4 text-white font-sen"><b>Edit Your Profile</b></h4> </div> <div class="my-1 py-1"></div> <hr class="border-t-1 border-t-black"> <div class="my-1 py-1"></div> <div class="py-3"> <input class=" p-2 w-[500px] rounded-sm max-sm:w-[300px]" type="text" name="fullname" id="name" placeholder="firstname" > </div> <div class="py-3"> <input class=" p-2 w-[500px] rounded-sm max-sm:w-[300px]" type="text" name="fullname" id="name" placeholder="lastname" > </div> <div class="py-3"> <input class=" p-2 w-[500px] border rounded-sm max-sm:w-[300px]" type="file" name="profile_pic" accept="image/*" id="profile_pic" > </div> <div class="py-3"> <input class=" p-2 w-[500px] border rounded-sm max-sm:w-[300px]" type="email" name="email" id="email" placeholder="email" > </div> <div class="py-3"> <textarea cols="30" rows="10" class="overflow-auto p-2 w-[500px] rounded-sm max-sm:w-[300px]" type="text" name="bio" id="title" placeholder="Say something about yourself.."></textarea> </div> <div class="py-3"> <button class="bg-white p-2 w-[100px] border rounded-sm max-sm:w-[100px]" type="submit" name="submit_btn" id="button" >submit</button> </div> </form> </div> </section> </main> {% endblock %} In the views.py file I have … -
What concerns should I have for a multiple hour long @transaction.atomic django background process?
I have a celery background task that runs and can take 5+ hours to complete. It is primarily creating new objects and it will generate around 100k or so new objects. If something were to go wrong during this I would like to roll it all back as if it never happened. My strategy for ensuring this is to wrap the background task in a @transaction.atomic. Since this is such a long running transaction is there anything I should be particularly concerned about? If I happen to fail after 4 hours do I need to worry about my Postgres database freezing up in production? Is there another way I should be doing this or is transaction.atomic the best strategy? I currently have it running in a @transaction.atomic block. It currently works fine in development but I have concerns that it may cause issues in production. -
Error "database couldn't be flushed" in pytest-django when adding live_server
When I run pytest with live_server, I see error: E django.core.management.base.CommandError: Database file:memorydb_default?mode=memory&cache=shared couldn't be flushed. Possible reasons: E * The database isn't running or isn't configured correctly. E * At least one of the expected database tables doesn't exist. E * The SQL was invalid. E Hint: Look at the output of 'django-admin sqlflush'. That's the SQL this command wasn't able to run. test_settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } pytest.ini [pytest] DJANGO_SETTINGS_MODULE = n3auto.settings.test_settings python_files = tests/**/*.py tests/*.py tests.py addopts = --create-db -p no:warnings --no-migrations conftest.py import pytest @pytest.fixture(autouse=True) def grant_db_access_to_all_tests(db): pass tests.py from app.models import MModel def test1(live_server): pass def test2(): assert MModel.objects.count() == 0 When I remove test1 with live_server, tests running without errors. -
mysqlclient failed on vercel
I am unable to deploy my because of this Error 1: Command failed: pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [16 lines of output] /bin/sh: mysql_config: command not found /bin/sh: mariadb_config: command not found /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-install-hwcmhfay/mysqlclient_c0e246e016eb466f916ce14b69432b1e/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-hwcmhfay/mysqlclient_c0e246e016eb466f916ce14b69432b1e/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-hwcmhfay/mysqlclient_c0e246e016eb466f916ce14b69432b1e/setup_posix.py", line 31, in mysql_config raise OSError("{} no I am expecting a clear explaination about problem and a clear solution Similar to this error but on vercel -
Error running WSGI application AttributeError: module 'juzgado10_pythonanywhere_com_wsgi' has no attribute 'application', how do i fix this?
I'm trying to deploy a web app I've made in wagtail on pythonanywhere and i keep bumping into errors and issues and its a nightmare honestly, apparently its a wsgi issue but i have no clue how to solve it. Here's my WSGI configuration file. # +++++++++++ DJANGO +++++++++++ # To use your own django app use code like this: """ WSGI config for juzgado10 project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/ """ import os import sys # ## assuming your django settings file is at '/home/juzgado10/mysite/mysite/settings.py' ## and your manage.py is is at '/home/juzgado10/mysite/manage.py' path = '/home/juzgado10/pagina-juzgado/juzgado10' if path not in sys.path: sys.path.insert(0, path) os.environ['DJANGO_SETTINGS_MODULE'] = 'juzgado10.settings.prod' # ## then: from django.core.wsgi import get_wsgi_application app = get_wsgi_application() And here's the error I get. 2023-04-17 10:06:11,483: Error running WSGI application 2023-04-17 10:06:11,484: AttributeError: module 'juzgado10_pythonanywhere_com_wsgi' has no attribute 'application' 2023-04-17 10:06:11,484: *************************************************** 2023-04-17 10:06:11,485: If you're seeing an import error and don't know why, 2023-04-17 10:06:11,485: we have a dedicated help page to help you debug: 2023-04-17 10:06:11,485: https://help.pythonanywhere.com/pages/DebuggingImportError/ 2023-04-17 10:06:11,485: *************************************************** 2023-04-17 10:06:12,005: Error running WSGI application 2023-04-17 10:06:12,005: AttributeError: module 'juzgado10_pythonanywhere_com_wsgi' has no attribute 'application' -
django.db.utils.IntegrityError and sqlite3.IntegrityError
I'm following a Django tutorial to train and make a simple poll site. At a certain point, when I need to get the server running and add questions to the polls, I come across the error codes below: django.db.utils.IntegrityError: NOT NULL constraint failed: polls_question.question_text sqlite3.IntegrityError: NOT NULL constraint failed: polls_question.question_text I expected to be able to add questions in the questions field created in the database, but I came across this mistakes. What do I do? -
Can't connect Django with MySQL
I'm facing an issue trying to connect Django with MySQL, I'm on MacOS with Monterey, I have already installed Python and MySQL with brew, additionally I have installed mysqlclient with pip3, also, I have already change the DATABASE conf in settings.py in my django project, but the error is always the same when I try to make migrations or migrate: django.core.exceptions.ImproperlyConfigured: 'django.db.backends.mysql' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'oracle', 'postgresql', 'sqlite3' Here is my database configuration: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'djangodatabase', 'USER': 'dbadmin', 'PASSWORD': '12345', 'HOST': 'localhost', 'PORT': '3306', } } Any idea about how to solve this? Thanks to all... change DATABASE configurations, and many others. -
How to stream local video using django
I"m using python-ffmpeg-video-streaming in my django project. I can able to generate mpd and m3u8 file successfully , but i didnt know how to serve these file using django views. I tried this approach but this is not working def stream_multi_quality_video(request): video_path = "./dashpath/dash.mpd" with open(video_path, "rb") as mpd_file: mpd_contents = mpd_file.read() # Set the response headers response = HttpResponse(mpd_contents, content_type="application/dash+xml") response["Content-Length"] = len(mpd_contents) return response after this I got chunk file not found error in browser console. Here is my frontend code for videojs <div class="video-container"> <video id="my-video" class="video-js" controls preload="auto" width="640" height="264" data-setup="{}"> <source src="{% url 'stream_video' %}" type="application/dash+xml"> </video> </div> <script> var player = videojs('my-video'); </script> -
use node modules in django
I want to build a qr-code scanner to my django web app. For that I currently am using jsQR. For some reason Django is not able to allocate the jsQR module needed for the script to run. snippet for html file: (on click on the button, webcam opens and it should scan for qr codes) <button id="qr-code-scanner">Scan QR Code</button> <video id="video" width="640" height="480" autoplay></video> <canvas id="qr-canvas" width="640" height="480"></canvas> ... <script type="module" src="{% static 'business_page/js/qr_scanner_fin_2.js' %}"></script> qr_scanner_fin_2.js file: import jsQR from './jsqr'; const constraints = { video: true }; const canvas = document.getElementById('qr-canvas'); const ctx = canvas.getContext('2d'); function startCamera() { navigator.mediaDevices.getUserMedia({ video: true }) .then((stream) => { const video = document.querySelector('video'); video.srcObject = stream; video.play(); video.addEventListener('loadedmetadata', () => { canvas.width = video.videoWidth; canvas.height = video.videoHeight; const scan = () => { ctx.drawImage(video, 0, 0, canvas.width, canvas.height); const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); const code = jsQR(imageData.data, imageData.width, imageData.height, { inversionAttempts: false, }); if (code) { console.log('QR code detected:', code.data); video.pause(); stream.getTracks().forEach(track => track.stop()); return; } requestAnimationFrame(scan); }; requestAnimationFrame(scan); }); }) .catch((error) => { console.error('Error accessing media devices.', error); }); } document.addEventListener('DOMContentLoaded', () => { console.log('DOMContentLoaded'); }); const scanButton = document.getElementById('qr-code-scanner'); scanButton.addEventListener('click', () => { console.log('scanButton click'); startCamera(); }); for some … -
'Request failed with status code 403', name: 'AxiosError', code: 'ERR_BAD_REQUEST'
So I have created a django-react E-commerce website. I have used rest framework to create api for making get and post request to the backend. Both get and rest requests are working fine when made with rest framework in built forms. But I am unable to make the same through my react frontend. Its giving me the 403 forbidden error. I am able to perform get request using the api through frontend facing issues just with post request. console error msg xhr.js:247 POST http://127.0.0.1:8000/api/create/ 403 (Forbidden) I have tried using axios as well as fetch to make those requests through react. I have tried all existing solution on stackoverflow. Here's how my react code looks like adduom.js import React from 'react' import { useState } from "react"; // import { useForm } from "react-hook-form"; import '../../App.css'; import Navbar from '../Navbar'; import axios from 'axios'; export default function AddUom() { const [obj, setobj] = useState({ uom: '' }) const addUom = async () => { console.log("hiii") const response = await fetch(`http://127.0.0.1:8000/api/customer/`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(obj) }); const data = await response.json(); console.log("add UOM called : \n"+data); } const handleSubmit = (e) => { e.preventDefault(); var … -
DRF serializer for questions that depend on multiple objects
I am trying to write a serializer which allows users to submit the answers to a quiz. However, the questions that should be answered depend on two separate things in the database. So, let's say we have these models:- class Day(models.Model): name = models.CharField() class Quiz(models.Model): name = models.CharField() class QuizQuestion(models.Model): quiz = models.ForeignKey(Quiz, related_name="questions") days = models.ManyToManyField(Day, related_name="questions") question = models.CharField() class QuizCompletion(models.Model): completed_by = models.ForeignKey(User) quiz = models.ForeignKey(Quiz) class QuizAnswer(models.Model): quizquestion = models.ForeignKey(QuizQuestion) quizcompletion = models.ForeignKey(related_name="answers", QuizCompletion) answer = models.CharField() So, to find the questions that the user has to answer for a particular quiz for a particular day, you'd need to do something like:- questions = quiz.questions.filter(days__id=day.id) I'm trying to create the serializer for submitting the answers to such a quiz so that it will check whether all of the questions have been answered. What is the best way to write this serializer? The days thing is the thing that's confusing me. Do I need a URL that includes BOTH the quiz ID and the day ID, so that I can get the right questions? class QuizCompletionSerializer(serializers.ModelSerializer): quiz = QuizSerializer() answers = QuizAnswerSerializer(many=True) class Meta: model = QuizCompletion fields = ["completed_by", "quiz", "answers"] def validate_answers(self, answers): # … -
Why my django-filter filters don't work. There is no error, the GET request arrives
Created filtering of Users objects. It worked for a while, but then it stopped. I can't understand what the problem is. Get request is sent( http://127.0.0.1:8000/staff/manager/user-list/?gender=M ). But the data on the page is not updated. There are no errors. What to do? class UserFilters(django_filters.FilterSet): class Meta: model = User fields = ('gender',) class ManagerUsersListView(ListView): template_name = 'manager/list_users_manager.html' model = User paginate_by = 7 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['users'] = User.objects.all() context['filter'] = UserFilters(self.request.GET, queryset=self.get_queryset()) return context def get_queryset(self, **kwargs): search_results = UserFilters(self.request.GET, self.queryset) self.no_search_result = True if not search_results.qs else False return search_results.qs Simplified version of HTML <form method="get"> {{ filter.form }} <input type="submit" class="btn btn-default add-to-cart" value="Filer"></input> </form> {% for u in users %} {{u.pk}} {{u.first_name}} {{u.gender}} {% endfor %} I broke my head......