Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django many to many not symmetrical parent implemntation. Reverse lookup is returning the childs, not parents
In models.py I have this model: class element (models.Model): element=models.Autofield(primary_key=true) parent_element=models.ManyToMayField('self',null=True,blank=True, related_name='parents',symmetrical=False) This relationship is implemented in database, by django, into a table with "from_element" (child, my element) and "to_element" (parents of my element) fields. The problems happens when I try to obtain the parents of a element with a reverse lookup,giving as result the elements that have my element as parent, the childs. Debugging the parents I see this: element.parents.source_field_name='to_element' element.parents.target_field_name='from_element' instead of element.parents.source_field_name='from_element' element.parents.target_field_name='to_element' Giving an example, if I create the element 1, and after I create the element 2 with element 1 as "parent" this is what I have: element.objects.get(element=1).parents.all() is 2 (his child, wrong) element.objects.get(parent=1) is 2 (his child, rigth) element.objects.get(element=2).parents.all() do not exist (wrong) element.objects.get(parent=2) do not exist (right) In database I have this: from_element is 2 and to_element is 1. But, as I said, parents.all() is looking from "to_element" to "from_element" Many to one and one to many are not the same, they have a direction. It is easy to define a one-to-many when you are using different models, define the foreign key into the "many" model and it's done, but not in 'self' case. Looking for information I always found "use a Foreign … -
Django check user.is_authenticated before UserCreationForm to prevent a user to signup twice
In Django, I am trying to prevent an already existing user to register (sign up) again. In my case, the user can sign up with a form. My approach is to check in views.py if the user already exists by checking is_authenticated upfront. If the user does not exist, then the form entries will be processed and the user will be created. The problem: if the user already exists, I would expect the condition request.user.is_authenticated to be True and the browser to be redirected to home. Instead, the evaluation goes on to process the form throwing (of course) the following error: Exception Value: duplicate key value violates unique constraint "auth_user_username_key" DETAIL: Key (username)=(john.doe) already exists. This is a sample of my views.py: def register_user(request): if request.method == "POST": if request.user.is_authenticated: messages.error(request, ('User already exists.')) return redirect('home') form = UserCreationForm(request.POST) if form.is_valid(): form.save() ... # do more stuff What am I missing? -
Most Efficient Way To Paginate Combined Queries From Multiple Models in Django Rest Framework
I am creating a social media website using DRF as my back-end. Recently, I noticed the "Home" feed getting too slow for comfort. I then realized that, even though I was using a a paginator, I am still serializing all "Feed Item" objects before paginating them. Take a look at the code below: # serialize reposts = RepostSerializer(reposts_query, many=True).data posts = SmallPostSerializer(feed_posts_query, many=True).data comments = FeedCommentSerializer(feed_comments_query, many=True).data #combine combined_posts_and_comments = list(chain(reposts, posts, comments)) # sort combined list by date feed_items = sorted( combined_posts_and_comments, key=lambda k: k["date"], reverse=True ) # paginate combined list paginator = Paginator(feed_items, self.page_size) How do I only fetch the necessary items for the selected page before serializing the feed items? I can not just slice the queries like [(page_size * page_num) - page_size:page_size * page_num], because after combining and paginating, it will create strange and inconsistent results when navigating to the next page. I also tried slicing like this: [:page_size * page_num]. However, as the page number increases, it gets slower and slower. I am sure somebody has ran into this problem before, how should I proceed? -
My CSS file won’t load. I try to search the internet but didn’t found a solution. can you assist me?
Hi for some reason my CSS file won’t load. I try to search the internet but didn’t found a solution. can you assist me ? My settings code I've tried every possible solution on the internet, but it's of no use. -
How to automatically start a python http server
I am using python http.server 80 to expose my downloaded files to my twilio whatsapp bot is there a way that as my django-twillio app starts it automatically runs the server on port 80 as well python -m http.server 80 -
DJANGO: Get ManyToMany objects through raw SQL query
Is it possible to get the many-to-many objects connected to a model through raw SQL? (using django.db.connection) Here are my simplified models: class Comment(models.Model): author = models.CharField(max_length=100) body = models.CharField(max_length=140) class Post(models.Model): title = models.CharField(max_length=100) body = models.TextField() comments = models.ManyToManyField(Comment) Here's the output when I query using SQL all posts: from django.db import connection cursor = connection.cursor() cursor.execute("SELECT * FROM home_post") all = cursor.fetchall() print(all) # output: [(1, 'First Post', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed.')] The comments many-to-many objects aren't returned. Any help? -
character "@" in the name of a variable in the django template
I have a dictionary in my views.py mydata = {'@model': 'wolfen', '@genre': 'fantastic', 'price: '350'} which I pass to the django view in a context like this context['mydata'] = mydata and in my view i display like this {{mydata.@model}} the problem is that the django template uses the "@" character for other tags. How to replace the "@" character to not display the following error Could not parse the remainder: '@model' from 'mydata.@model' thank you -
Dynamically generate for loops to create lists from a dictionary
variations = { 'size':{'small':'Small', 'medium':'Medium', 'large':'Large'}, 'quantity':{'20l':'20l', '10l':'10l', '5l':'5l'}, 'color':{'red':'Red', 'blue':'Blue', 'green':'Green'} } var_list = [[i,j,k] for i in variations['color'] for j in variations['size'] for k in variations['quantity']] You can also write the above code as: var_list = [] for i in variations['color']: for j in variations['size']: for k in variations['quantity']: comb = [] comb.append(i) comb.append(j) comb.append(k) Var_list.append(comb) Both the var_list will output: [['red', 'small', '20l'], ['red', 'small', '10l'], ['red', 'small', '5l'], ['red', 'medium', '20l'], ['red', 'medium', '10l'], ['red', 'medium', '5l'], ['red', 'large', '20l'], ['red', 'large', '10l'], ['red', 'large', '5l'], ['blue', 'small', '20l'], ['blue', 'small', '10l'], ['blue', 'small', '5l'], ['blue', 'medium', '20l'], ['blue', 'medium', '10l'], ['blue', 'medium', '5l'], ['blue', 'large', '20l'], ['blue', 'large', '10l'], ['blue', 'large', '5l'], ['green', 'small', '20l'], ['green', 'small', '10l'], ['green', 'small', '5l'], ['green', 'medium', '20l'], ['green', 'medium', '10l'], ['green', 'medium', '5l'], ['green', 'large', '20l'], ['green', 'large', '10l'], ['green', 'large', '5l']] var_list contains 3 for loops based on the 3 dictionaries in variations. How can we dynamically write the above code so that if more or less dictionaries are present in variations the for loops in var_list can also get adjusted? e.g if 'brand' is also present in variations, a for loop for this 'brand' should be … -
how to know which app is running in background and save all spendig time of that?
I want to know can I increase my time counter when specific app is running in background of operating system and save spending time in db? is it posiible to solve this problem with django? e.g:I want to open photoshop with an icon in my website(in user`s computer) then I track what time they spend in that app. I think I need a script on users computer to send me feedback of processes or an desktop app to track the processes. -
How to send POST request using Julia lang HTTP library to a Django RESTFUL API (DRF)
There is very limited documentation when it comes to the HTTP library in Julia Lang. Not just that, but there are no up to date Stack Overflow questions regarding the HTTP library in general. With that said, how do you send POST requests using Julia + HTTP to a Django Restful API (DRF)? -
Create and edit form with multiple Django files
could someone tell me how to save multiple files in the post method of my form, I can only save 1 file, not the ones I have tried to upload. Files = models.FileField(upload_to="alumno/archivos/%Y/%m/%d", null=True, blank=True, verbose_name='Archivos') That's what the field is called in my model Student. Then in my post method in the view I have the following code, but it doesn't save everything, as I said it only saves 1 file. def post(self, request, *args, **kwargs): data = {} files = request.FILES.getlist('Files') try: action = request.POST['action'] if action == 'edit': form = self.get_form() for f in files: Alumno.objects.update(Files=f) data = form.save() else: data['error'] = 'No ha ingresado a ninguna opción' except Exception as e: data['error'] = str(e) return JsonResponse(data) In this case as it says update in Alumno.objects because I am doing the edit, I have the same problem as with the create. Please could someone help me? Regards I want to be able to save or edit two or more files in the Pupil model. -
Django and ajax - data returning value but not populating field
I am new to Django and Ajax. I have a dropdown that is populated from a database. I want another field to populate based on the selection made in the dropdown. I am getting the return value, but it is not populating the form field. Console.log shows the value being returned. It just never shows on the form field and I am sure the field name is correct. In the browser I get 600. How do I get the 600 into the #id_Deductable field? Any help would be greatly appreciated. ` <script> $("#id_Primary_Plan").change(function () { var url = $("#BaseQuoteForm").attr("data-agent-url"); // get the url of the `load_cities` view var PlanData = $(this).val(); // get the selected country ID from the HTML input $.ajax({ // initialize an AJAX request url: url, // set the url of the request (= localhost:8000/hr/ajax/load-cities/) data: { 'PlanData_id': PlanData // add the country id to the GET parameters }, success: function (data) { // `data` is the return of the `load_cities` view function console.log(data); $("#id_Deductable").text(data); // replace the contents of the city input with the data that came from the server } }); }); </script> ` -
Django many to many not symmetrical parent implementation. Reverse lookup is returning the child, not parents
Hi, In models.py I have this model: class element (models.Model): element=models.Autofield(primary-key=true) parent_element=models.ManyToMayField('self',null=True,blank=True, related_name='parents',symmetrical=False) This relationship is implemented in database, by django, into a table with "from_element" (child, my element) and "to_element" (parents of my element) fields. The problems happens when I try to obtain the parents of a element with a reverse lookup,giving as result the elements that have my element as parent, the childs. Debugging the parents I see this: element.parents.source_field_name='to_element' element.parents.target_field_name='from_element' instead of element.parents.source_field_name='from_element' element.parents.target_field_name='to_element' Giving an example, if I create the element 1, and after I create the element 2 with element 1 as "parent" this is what I have: element.objects.get(element=1).parents.all() is 2 (his child, wrong) element.objects.get(parent=1) is 2 (his child, rigth) element.objects.get(element=2).parents.all() do not exist (wrong) element.objects.get(parent=2) do not exist (right) In database I have this: from_element is 2 and to_element is 1. But, as I said, parents.all() is looking from "to_element" to "from_element" Many to one and one to many are not the same, they have a direction. It is easy to define a one-to-many when you are using different models, define the foreign key into the "many" model and it's done, but not in 'self' case. Looking for information I always found "use a … -
the method form.is_valid always returns always
I do my own project and I'm stuck on this problem. My form always returns False when calling form.is_valid. This is my code: forms.py: I need to let user to choose the size he need from the list of available sizes, so I retrieve sizes from the database and then make a ChoiceField with variants of these sizes. class CartAddProductForm(ModelForm): class Meta: model = Product fields = ['sizes'] def __init__(self, pk: int, *args, **kwargs) -> None: super(CartAddProductForm, self).__init__(*args, **kwargs) sizes = tuple(Product.objects.get(pk=pk).sizes) sizes_list = [] for item in sizes: sizes_list.append((item, item)) self.fields['sizes'] = forms.ChoiceField(choices=sizes_list) views.py: This func creates the form def product_detail(request: WSGIRequest, product_id: int, product_slug: str) -> HttpResponse: product = get_object_or_404(Product, id=product_id, slug=product_slug, available=True) categories = Category.objects.all() cart_product_form = CartAddProductForm(instance=product, pk=product_id) return render(request, 'shop/product/detail.html', {'product': product, 'categories': categories, 'cart_product_form': cart_product_form}) When user pushes the button 'Add to cart' he is redirected to the other page with details of his cart. So here's the problem: @require_POST def add_to_cart(request: WSGIRequest, product_id: int) -> HttpResponseRedirect: cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(instance=product, pk=product_id) if form.is_valid(): cd = form.cleaned_data print(f'cd = {cd}') cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) else: print(f'form.is_valid = {form.is_valid()}') print(f'request.POST = {request.POST}') print(f'form.errors = {form.errors}') print(f'form.non_field_errors = {form.non_field_errors}') field_errors = … -
How to use wkhtmltopdf in Windows dockerized Django app
I have an invoicing app that I made using Django. So far the invoicing app works fine without docker by specifying the wkhtmltopdf path in my windows as follows '''config = pdfkit.configuration(wkhtmltopdf='C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe')''' However, I decided to rebuild the app using Docker for deployment purposes. As a result, I am receiving the following error when I run the same app using docker. " OSError: No wkhtmltopdf executable found: "C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe" I have researched the internet on wkhtmltopdf docker image files but solutions are not made for windows or clear to me. Here Is my Docker file: # Pull base image FROM python:3.10.4-slim-bullseye # Set environment variables ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt # Copy project COPY . . Can anyone please help me? which methods that I have to employ so that I can print pdfs from my docker environment? I am novice to Docker. Thanks In Advance -
Wrong Django User Creation
I created Users inside the admin view with my custom User model: class User(AbstractUser): phone_number = models.CharField(max_length=64) department = models.CharField(max_length=128) misc_settings = models.JSONField(null=True, blank=True) RelatedGroup = models.ManyToManyField(Group, related_name='GroupMember') when I created them, they appear there and seem to have everything i wanted, a username and an id/pk: [thats the screenshot of the admin] https://i.stack.imgur.com/RqJEB.jpg) However, when I try to check for them in the shell, they don't seem to exist properly? In [1]: from accounts.models import User In [2]: antoine = User(id=4) In [3]: antoine.id Out[3]: 4 In [4]: b = User(username="antoine") In [5]: b.id In [6]: b.username Out[6]: 'antoine' In [7]: antoine.username Out[7]: '' I need them to have, both a username and an id, how come they dont seem to have it? I'm honestly pretty new to both django and databases, so I dont get why this straight forward approach doesn't work type here -
Tailwind UI components not working in Django templates
I'm trying to use tailwind UI components in my Django project (I use Djang as Fullstack framework, not Django's REST Framework). The components I want to use require Vue.js or React (I went with Vue.js). When I copy & paste the components into my Django templates, the Vue.js code doesn't seem to work. By default, it's loaded in a <script setup> tag, and I tried loading it from a cdn like so: <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script type='text/javascript'>...</script> But it still doesn't work. I'm using django-tailwind to run tailwind. Anybody else who set up Tailwind UI Components in Django Templates and can help me with this? -
Django NOT NULL constraint error on imaginary field
I have been getting the following error. django.db.utils.IntegrityError: NOT NULL constraint failed: doctor_owner.doc_name This error primarily arises on when I save the owner information using .save() and the error it gives is on doc_name, which is not present in the model definition of the class Owner. I am clueless why it is giving such an error. My model is attached below: . This is my model description: from django.db import models # Create your models here. from base.models import BaseModel class Owner(BaseModel): owner_id = models.CharField(max_length=50) owner_name = models.CharField(max_length=250) class Pet(BaseModel): owner = models.ForeignKey(Owner, on_delete=models.CASCADE) pet_name = models.CharField(max_length=100) pet_age = models.DecimalField(max_length=3, decimal_places=2, max_digits=50) pet_specie = models.CharField(max_length=250) pet_gender = models.CharField(max_length=1) class Medicine(BaseModel): medicine_name = models.CharField(max_length=250) frequency = models.CharField(max_length=100) duration = models.CharField(max_length=100) class Prescription(BaseModel): pet = models.ForeignKey(Pet, on_delete=models.CASCADE) medicine = models.ForeignKey(Medicine, on_delete=models.CASCADE) class Treatment(BaseModel): pet = models.ForeignKey(Pet, on_delete=models.CASCADE) owner = models.ForeignKey(Owner, on_delete=models.CASCADE) doc_name = models.CharField(max_length=250) prescription = models.ForeignKey(Prescription, on_delete=models.CASCADE) -
Quickly switch out external services, or inject mock services, using a factory and import_string, a good pattern?
I wanted a quick way to be able to switch out queue services, and use any one of Kafka, RabbitMQ, etc. or even replace with a Mock queue service. So I set it up using import_string. There is an Abstract Base Class (ABC), queue factory, the implementations and a value in settings.py which says which queue to use. class Producer(ABC): """Abstract producer.""" @abstractmethod def send_message(self, queue_name, message): """Send a message to a queue.""" pass class KafkaProducer(Producer): """Kafka producer.""" def send_message(self, queue_name, message): """Send a message to a Kafka queue.""" send_message_to_kafka(message) class QueueFactory: """Queue factory.""" @staticmethod def get_producer(): """Get configured queue producer.""" return import_string(settings.QUEUE_PRODUCER_CLS)() In settings.py: QUEUE_PRODUCER_CLS = "queues.kafka.KafkaProducer" # set to Kafka queue QUEUE_PRODUCER_CLS = "queues.tests.mock_queue.MockProducer" # set to Mock queue Then you can call it like so: QueueFactory.get_producer().send_message("my-queue", "my message") Not sure if it's the best way, does this make sense? Just feel like it's quite a bit of boilerplate code. -
How can i connect users to add their own recipes?
Im creating a blog-app where users can create an account and i want them to be able to add their recipes to my site. I'm having some trouble to set these up and am currently getting these errors in my browser when clicking the button for "add your own recipes here: TypeError at /create/ Post() got an unexpected keyword argument 'initial' Request Method: GET Request URL: http://localhost:8000/create/ Django Version: 3.2.16 Exception Type: TypeError Exception Value: Post() got an unexpected keyword argument 'initial' Exception Location: /workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/base.py, line 503, in init Python Executable: /home/gitpod/.pyenv/versions/3.8.11/bin/python3 Python Version: 3.8.11 Python Path: ['/workspace/bake-me-a-cake', '/home/gitpod/.pyenv/versions/3.8.11/lib/python38.zip', '/home/gitpod/.pyenv/versions/3.8.11/lib/python3.8', '/home/gitpod/.pyenv/versions/3.8.11/lib/python3.8/lib-dynload', '/workspace/.pip-modules/lib/python3.8/site-packages', '/home/gitpod/.pyenv/versions/3.8.11/lib/python3.8/site-packages'] Server time: Wed, 30 Nov 2022 15:12:25 +0000 My code is as following (in views.py): from django.shortcuts import render, get_object_or_404, reverse from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from django.views import generic, View from django.http import HttpResponseRedirect from .models import Post, Comment from .forms import CommentForm from django import forms class PostList(generic.ListView): """ View published recipes and how many are viewable per page """ model = Post queryset = Post.objects.filter(status=1).order_by('created_on') template_name = 'index.html' paginate_by = 6 class PostDetail(View): """ view comment and likes information """ def get(self, request, slug, *args, … -
problem with the "@" character in the django template
I'm passing a dictionary in the django view with the context key names come from an external json file mydata = {'@item': 'Kotokeno', '@model: '200', 'price': '320'} context['mydata'] = mydata and in the view I display like this {mydata.@item}} the problem and with the "@" character which is used in the django template engine and it gives me an error Could not parse the remainder: '@item' from 'mydata.@item' how can I either escape in the template this character or maybe in views.py rename the key names (with pop()) or any other solution. thank you -
Nginx/UWSGi/Django Stack "AppRegistryNotReady("Apps aren't loaded yet.")"
I have been racking my brain on this for probably about 32 hours total at this point, and any help is welcome. Currently stuck at an 'Internal Server Error' in browser. Error Message/Traceback: $ python3 manage.py check Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/django/django_venv/lib64/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/django/django_venv/lib64/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute settings.INSTALLED_APPS File "/home/django/django_venv/lib64/python3.6/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/home/django/django_venv/lib64/python3.6/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/home/django/django_venv/lib64/python3.6/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/django/django_venv/django_site/settings.py", line 17, in <module> import urls File "/home/django/django_venv/django_site/urls.py", line 25, in <module> path("/data_sources/", include("data_sources.urls")), File "/home/django/django_venv/lib64/python3.6/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/home/django/django_venv/django_site/data_sources/urls.py", line 3, in <module> from . import views File "/home/django/django_venv/django_site/data_sources/views.py", line 2, in <module> from summary.models … -
ERROR: admin.E108 and admin.E116 Django Framework Python
<class 'blog.admin.CommentAdmin'>: (admin.E108) The value of 'list_display[4]' refers to 'active', which is not a callable, an attribute of 'CommentAdmin', or an attribute or method on 'blog.Comment'. <class 'blog.admin.CommentAdmin'>: (admin.E116) The value of 'list_filter[0]' refers to 'active', which does not refer to a Field. I am receiving these two errors. This is my models.py code: from django.contrib.auth.models import User # Create your models here. STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updatedOn = models.DateTimeField(auto_now= True) content = models.TextField() createdOn = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-createdOn'] def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() createdOn = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=False) class Meta: ordering = ['createdOn'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) This is my admin.py code: from django.contrib import admin from .models import Post, Comment # Register your models here. class PostAdmin(admin.ModelAdmin): list_display = ('title', 'slug', 'status','createdOn') list_filter = ("status", 'createdOn') search_fields = ['title', 'content'] prepopulated_fields = {'slug': ('title',)} @admin.register(Comment) class CommentAdmin(admin.ModelAdmin): list_display = ('name', 'body', 'post', 'createdOn', 'active') list_filter = ('active', 'createdOn') search_fields = ('name', 'email', 'body') … -
How can I compare the user's answer in the quizz with the correct answer in the database?
How can I compare the user's answer in the quizz with the correct answer in the database and give a point if the answer is correct? currently i get all answers wrong, after the quiz.I Want, if the user choice the right answer, that he get a point and if the answer wrong than get he 0 points. views.py def math(request): if request.method == 'POST': print(request.POST) questions = QuesModel.objects.filter(kategorie__exact="mathematics") score = 0 wrong = 0 correct = 0 total = 0 for q in questions: total += 1 answer = request.POST.get(q.question) if q.ans == answer: score += 10 correct += 1 else: wrong += 1 percent = score / (total * 10) * 100 context = { 'score': score, 'time': request.POST.get('timer'), 'correct': correct, 'wrong': wrong, 'percent': percent, 'total': total, } return render(request, 'result.html', context) else: questions = QuesModel.objects.all() context = { 'questions': questions } return render(request, 'mathe.html', context) model.py class QuesModel(models.Model): Categorie= ( ("mathematics", "mathematics"), ("Business Administration", "Business Administration"), ) categorie= models.CharField(max_length=400, null=True, choices=Categorie) explaination= models.CharField(max_length=400, null=True) user = models.ForeignKey(Profile, null=True, on_delete=models.SET_NULL) question = models.CharField(max_length=200, null=True) op1 = models.CharField(max_length=200, null=True) op2 = models.CharField(max_length=200, null=True) op3 = models.CharField(max_length=200, null=True) op4 = models.CharField(max_length=200, null=True) ans = models.CharField(max_length=200, null=True) def __str__(self): return self.question … -
Global Pagination not working on DRF Project
I have written an API on DRF which returns a list of data based on certain conditions, but the data is very large and global pagination is not applying on it. As a result, speed slows down and therefore, data is not shown properly on a single page. I have adding following code in settings.py file: REST_FRAMEWORK = { "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination", "PAGE_SIZE": 10 } This is my API: class TeacherViewSet(ModelViewSet): queryset = Teacher.objects.all() serializer_class = serializers.TeacherSerializer authentication_classes = [TokenAuthentication] def list(self, request, *args, **kwargs): response = [] for teacher in queryset: name = Student.objects.filter(teacher=teacher).values("name") res = {"name": name} response.append(res) return Response(response) Any thing wrong I am doing?