Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add css file to my css_settings in settings.y
I`m using django-select2 but its not important and i want to add some new css styles to that settings but if i add them i got an error because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. settings.py SELECT2_CSS = [ os.path.join(BASE_DIR, 'static_src/css/style.css') ] -
How can I use django EAV in the models
I want to create something similar to Microsoft Access Design View in Django model using the models below. After doing my own research, the only way to make that happen is by using Django EAV. However, as a beginner in Django, I don't actually know how to make that happen. class Type(models.Model): TYPE_OF_DATA = ( ('Number', 'Number'), ('character', 'character'), ('boolean', 'boolean'), ('date', 'date'), ('image', 'image'), ) data_type = models.CharField(max_length=1000, choices= TYPE_OF_DATA) def __str__(self): return self.data_type class Column(models.Model): name = models.CharField(max_length=100) selec_type = models.ForeignKey(Type, on_delete= models.CASCADE) class Table(models.Model): number = models.IntegerField() character = models.CharField(max_length=30) check_box = models.BooleanField() date = models.DateField() image = models.ImageField(upload_to='image-table') As you can see using Django modelFormSet I successfully created 30 Column in the form: From .forms import ColumnForm From django.forms import modelformset_factory def design(request): ColumnFormSet = modelformset_factory(Column, fields = ('name', 'selec_type'), extra=30) formset = ColumnFormSet if request.method == 'POST': formset = ColumnFormSet(request.POST) if formset.is_valid(): formset.save() return redirect('Home') else: formset = ColumnFormSet() return render (request, 'design.html', {'formset':formset}) Using this view, a user can create a name of a field and assign it to the data type that a user want the field to be stored. My problem here is the Table model, where user can store all the … -
How to post data from one model and retrieve to another model of the same app using Django rest framework
I have two models which are related by one to many relationship. I want to use the first model called BedNightReturn to post data and another one called BedNightReturnAssessment to calculate the data post and retrieve data. My models are as follows:- class BedNightReturn(models.Model): room_type = models.CharField(max_length=50) number_of_rooms = models.PositiveSmallIntegerField() price_per_night = models.DecimalField(max_digits=10, decimal_places=2) days_in_month = models.PositiveSmallIntegerField() class Meta: verbose_name = 'BedNightReturn' verbose_name_plural = 'BedNightReturns' def __str__(self): return f'{self.room_type}' class BedNightReturnAssessment(models.Model): assessment = models.ForeignKey(BedNightReturn, related_name = "assessments", on_delete=models.CASCADE) class Meta: verbose_name = 'BedNightReturnAssessment' verbose_name_plural = 'BedNightReturnAssessments' def __str__(self): return f'{self.assessment.room_type}' @property def potential_turnover(self) -> float: days_in_month = 30 return float(days_in_month) * float(self.assessment.number_of_rooms) * float(self.assessment.price_per_night) @property def actual_turnover(self) -> float: return float(self.assessment.days_in_month) * float(self.assessment.number_of_rooms) * float(self.assessment.price_per_night) And serializers are as follows:- class BedNightReturnSerializer(ModelSerializer): class Meta: model = BedNightReturn fields = ( 'id', 'room_type', 'number_of_rooms', 'price_per_night', 'days_in_month', ) class BedNightReturnAssessmentSerializer(ModelSerializer): assessment = BedNightReturnSerializer() potential_turnover = ReadOnlyField() actual_turnover = ReadOnlyField() class Meta: model = BedNightReturnAssessment fields = ( 'id', 'assessment', 'potential_turnover', 'actual_turnover', ) And views are:- class BedNightReturnViewSet(ModelViewSet): queryset = BedNightReturn.objects.all() serializer_class = BedNightReturnSerializer class BedNightReturnAssessmentViewSet(ModelViewSet): queryset = BedNightReturnAssessment.objects.all() serializer_class = BedNightReturnAssessmentSerializer And urls:- from django.urls import include, path from rest_framework import routers from bednightlevy.views import ( BedNightReturnAssessmentViewSet, BedNightReturnViewSet, ) router = routers.DefaultRouter(trailing_slash … -
Is there any way to have end to end type safety in a website with React and Typescript as the frontend and Django as the backend?
I want to build a website with NextJS as the frontend and Django as the backend. I wanted to know if there was any way to ensure client to server type safety in my stack. Although I have searched for many libraries, but there doesn't seem to be any. The closest library I found was mypy, which ensured type safety in the backend, but not between the server and the client like tRPC. -
'tuple' object has no attribute 'quantity' django
I'm trying to do a cart system where an user can add a product to the cart and if it was already in there I would add one of it but I keep getting the error "'tuple' object has no attribute 'quantity' django". class OrderItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) cart = models.BooleanField(default=True) order = models.BooleanField(default=False) class Orders(models.Model) : user = models.ForeignKey(User, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) def add_to_cart(request, pk) : item = get_object_or_404(Product, pk=pk) order_item = OrderItem.objects.get_or_create( item = item, user = request.user, order = False ) order_qs = Orders.objects.filter(user=request.user) if order_qs.exists(): order = order_qs[0] if order.items.filter(item__pk=item.pk).exists() : order_item.quantity += 1 order_item.save() return redirect("product-detail", pk = pk) else: order.items.add(order_item) return redirect("product-detail", pk = pk) else: order = Orders.objects.create(user=request.user) order.items.add(order_item) return redirect("product-detail", pk = pk) -
DRF set auth_token to httponly cookie
I use djoser library for TokenAuthentication. But I don't want to send access_token to frontend. Because it can't save it in a secure way. So I changed TokenCreateView in this way: from djoser.views import TokenCreateView class TokenCreateView(TokenCreateView): def _action(self, serializer): token = utils.login_user(self.request, serializer.user) token_serializer_class = settings.SERIALIZERS.token response = Response() data = token_serializer_class(token).data response.set_cookie( key = 'access_token', value = data['auth_token'], secure = False, httponly = True, samesite = 'Lax' ) response.data = {"Success" : "Login successfully","data":data} return response I put access_token to httponly cookies. And created a middleware: def auth_token(get_response): def middleware(request): # when token is in headers in is not needed to add in from cookies logger.error(request.COOKIES.get('access_token')) if 'HTTP_AUTHORIZATION' not in request.META: token = request.COOKIES.get('access_token') if token: request.META['HTTP_AUTHORIZATION'] = f'Token {token}' return get_response(request) return middleware MIDDLEWARE = [ ... 'apps.profiles.middlewares.auth_token', ... ] This middleware adds access_token from cookies to headers. Now the frontend doesn't have an accecc to auth_token. And it is more difficult to steal the auth_token. Is this approach appropriate? -
Timeout after 30s waiting on dependencies to become available: [tcp://mathesar_db:5432]
I tried running sudo docker compose --profile dev up but everytime it fails to bring the server up with the same exact reason - Timeout after 30s waiting. I also tried restarting the docker service and killing all the processes on port 5432, but it didn't help. [+] Running 3/0 ⠿ Container mathesar_db Created 0.0s ⠿ Container mathesar_service_dev Cr... 0.0s ⠿ Container mathesar-watchtower-1 C... 0.0s Attaching to mathesar-watchtower-1, mathesar_db, mathesar_service_dev mathesar-watchtower-1 | time="2023-03-24T06:55:57Z" level=debug msg="Sleeping for a second to ensure the docker api client has been properly initialized." mathesar_db | mathesar_db | PostgreSQL Database directory appears to contain a database; Skipping initialization mathesar_db | mathesar_db | 2023-03-24 06:55:57.217 UTC [1] LOG: starting PostgreSQL 13.10 (Debian 13.10-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit mathesar_db | 2023-03-24 06:55:57.218 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 mathesar_db | 2023-03-24 06:55:57.218 UTC [1] LOG: listening on IPv6 address "::", port 5432 mathesar_db | 2023-03-24 06:55:57.384 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" mathesar_db | 2023-03-24 06:55:57.550 UTC [26] LOG: database system was shut down at 2023-03-24 06:55:17 UTC mathesar_db | 2023-03-24 06:55:57.595 UTC [1] LOG: database system is ready to accept connections mathesar-watchtower-1 | time="2023-03-24T06:55:58Z" level=debug … -
How to use render_foo() in a table made with django-tables2 but for dynamically generated columns?
i have a table Comparativ that is created using django-tables2. In this table I use the __init__ method to generate columns dynamically by getting some unique values("nrsl") from a model(SLCentruDeCost). for col in extra_cols creates the columns with name of col. In these columns I need to make some calculations, example: getting the name of the column and filtering a model by that name and getting the sum of a attribute that correspond to the filter. class Comparativ(tables.Table): def __init__(self, data, **kwargs): slcd = SLCentruDeCost.objects.filter(centrudecost_id=self.pk).values_list('nrsl', flat=True).distinct() if slcd: extra_cols=[] extra_cols = slcd for col in extra_cols: self.base_columns[col] = tables.Column(accessor=f'nrsl.{col}', verbose_name=col.replace("_", " ").title(),orderable=False) # i should set the render method for each new column here, but i don't know how super(Comparativ, self).__init__(data, **kwargs) I know that there the possibility to use the render_foo() function to render the values for a specific column, but that does not help me with the dynamically generated columns. Please help -
Django session storage and retrieval not working, can't pass value within view
I have a django view that I am using to process a payment.. This view has two different 'stages', and will do something different depending on the value of stage which is passed as a hidden value on each. This is my view (trimmed down for this question) at the moment: def takepayment(request, *args, **kwargs): if request.method == 'POST': form = paymentForm(request.POST) stage = request.POST.get('stage', False); firstname = request.POST.get('firstname', False); if (stage == "complete"): firstname = request.session['firstname'] return render(request, "final.html", {'firstname': firstname) if (amount > 1): if form.is_valid(): firstname = form_data.get('firstname') request.session['firstname'] = firstname return render(request, "payment.html") else: if form.is_valid(): form_data = form.cleaned_data amount = form_data.get('amount') request.session['firstname'] = firstname return render(request, "payment.html", {'form': form, 'amount': amount}) return render(request, "payment.html") In the section of the view where stage == "complete", firstname always reports as false. I am unclear as to why the session is not storing the firstname variable. Everything seems to be working as it should (aside from the obvious), so I'm unsure why this isn't working. I also set SESSION_SAVE_EVERY_REQUEST to True in settings.py and ran manage.py migrate as it was a suggestion for someone having a similar issue, however it made no difference in this case. I have … -
I want to show the password on click the button in django
In django ,I want to show the password on click the button but It is working for only one field .I want to show the password on clicking the relative button Here is my template code {% if passwords %} <div class="body"> <div class="origin"> <input type="number" name="noofpwds" value={{no}} disabled hidden> <table class="table table-borderless" id="tab"><h1>your passwords </h1> <div class="parent"> {% for pwd in passwords %} <div> <input type="text" class="span"value={{pwd.field}} readonly> <input type="password" placeholder="type old password" value={{pwd.pwd}} id="pwd" class="input" required> <button class="btn btn-primary" onclick="showHide()" id="btn">show</button> </div> <script> function showHide() { var showText=document.getElementById("btn"); var input=document.getElementById("pwd"); if (input.getAttribute("type") === "password") { input.setAttribute("type", "text"); showText.innerText = "hide"; } else { input.setAttribute("type", "password"); showText.innerText = "show"; } } </script> {% endfor %} </div> <tr class="submit-btn"> <td > <a href="{% url 'updatepwd' %}" ><button class="btn btn-primary" type="submit">update password</button></a> </td> </tr> </table> {{passwords.pwd}} </div> </div> {% endif %} All buttons are working for only one field I want to show the password on clicking the respective button -
modal appearing with modal backdrop in side
I am new to html and trying to implement bootstrap modal dialog but modal backdrop(Not sure about the exact name) is appearing on left side of it ,how do i resolve this I have already tried these : z-index: 1; data-backdrop="false" Adding to body with $('#exampleModalLong').appendTo($('body')); this is my modal : <div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true" data-backdrop="false"> <div class="modal-dialog modal-dialog-centered" role="document" id="modalDocument"> <div class="modal-content" id="modalContent"> <div class="modal-header" id="modalHeader"> <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> the CSS i have configured with modal : #exampleModalLong { left: 0; right: 0; top: 0; bottom: 0; margin: auto; position: absolute; width: 75%; height: 75%; background: aqua; z-index: 1; } method to display modal : function displayModel(message) { $('#exampleModalLong').modal('show') } Please help me resolve this -
Patch request in Django Rest Framework
I am creating a backend for online shopping. GET, POST are working fine but I am unable to configure PATCH request. I want to have it in the detailed view of an item with the url endpoint <int:item_id>/ Here is models.py: from django.db import models # Create your models here. class Item(models.Model): name = models.TextField() category = models.TextField() brandName = models.TextField() deleted = models.BooleanField(default=False) image = models.ImageField(upload_to='item_cover', blank=True, null=True) The views.py: class ItemList(APIView): # permission_classes = (IsAuthenticated,) def get(self, request, *args, **kwargs): items = Item.objects.all() serializer = listSerializer(items, many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): serializer = itemSerializer(data=request.data) if serializer.is_valid(): serializer.save() else: print(serializer.errors) return Response({"Status": "Added"}) class detailedItem(APIView): def get(self, request, item_id, *args, **kwargs): items = Item.objects.filter(pk=item_id) serializer = listSerializer(items, many=True) return Response(serializer.data) def patch(self, request): try: obj = ?? serializer = itemSerializer(obj, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=200) And the urls.py: urlpatterns = [ path('', views.ItemList.as_view(), name='item-list'), path('<int:item_id>/', views.detailedItem.as_view()), path('search/<str:search_query>/', views.FilteredItemList.as_view()), ] What shall I write in the object= to make it work? I have tried reading example of PATCH requests but still unable to get the things the way I want. -
Better alternative for passing complex object from template to views.py on POST call
In views.py on GET call, I create a random list of questions (its a complex object, list of dictionaries) and I send that list to the template (HTML) file using return render(request, 'some_page.html', args). I show one question at a time and once user enters the answer and clicks next, the next question is shown and so on. On every 'next' click, the answer has to be stored back in the database. What are my options on how can I send the answer to the backend while directing the user to the next question? An important thing to note here is that once that list of questions is generated, I cannot generate it again. I have to either save that list somewhere for this instance or pass it to and from views.py and template on every call. I think passing the list on every call is not an ideal solution and looking for a better suggestion. I show the questions in HTML one by one and there is a current index variable which i managed using JS. This is what the end of my GET function in views.py looks like: final_data = [very, complicatedly, ordered, list] final_data = json.dumps(final_data) args … -
Does Django admin support regex url?
I writed something like this: url(r'^oog\d{3}/', admin.site.urls) But when I open admin site, then visit some model. It show me the url is 0.0.0.0:8000/oog000/app... and it could not open. Thanks. -
Retrieving database object in Django using get_absolute_url method of a model
I'm working on a blog website where am using the get_absolute_url method to generate a url for the detail view of a blog post. Then I noticed that all post objects published around 00:00 to 01:00am have the date of the previous day. But when the date and time for the publication of the post is display on the browser it reads the correct date. The bug only appears on the url generated by the get_absolute_url which is used in the views.py file to retrieve the details of the post from the database. I have tried changing the Timezone setting in the settings.py file from my timezone to UTC and nothing. -
Avoid having to pass arguments to update
Is it possible in django to replace: MyModel.objects.get_stuff_to_close_query_set(time).update( status="closed", open_time=None, opener=None ) with: MyModel.objects.my_custom_query_set(time).close() where close() is doing the same thing as update in the first statement? If so, how do I implement close()? Additionally, is it possible to hide the query set by doing something like: MyModel.objects.close_stuff(time) -
Remove Margin from Paragraphs in CKEditor5
I am working on a project where I am utilizing the django-ckeditor package and wish to remove the margin on top and below paragraph elements. Unfortunately, I am having a lot of difficulty doing so. To add context, I am working with CKEditor 5. Is there a way to affect the styling using the configuration available with the django-ckeditor package, or some other way via CSS? I initially thought to try targeting the element via traditional CSS: .cke_editable p { margin: 0 !important; } However this caused no change. -
React and Django REST Framework login system
I'm trying to create a simple login system using React and Django Rest Framework. The userLogin function works but the userLogout doesn't and returns an error. Error details: POST http://127.0.0.1:8000/api/logout/ 403 (Forbidden) Uncaught (in promise) Status: 403 "CSRF Failed: Origin checking failed - http://127.0.0.1:3000 does not match any trusted origins." AuthContext.js import React, { createContext, useState, useEffect } from "react"; import axios from "axios"; const AuthContext = createContext(); export default AuthContext; export const AuthProvider = (props) => { axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.xsrfHeaderName = "X-CSRFToken"; axios.defaults.withCredentials = true; const api = axios.create({ baseURL: "http://127.0.0.1:8000/api/", }); const [user, setUser] = useState( () => JSON.parse(localStorage.getItem("user")) || null ); const [error, setError] = useState(null); const userLogin = async (email, password) => { try { const { data } = await api.post("login/", { username: email, password: password, }); if (data.error) { setError(data.error); } else { localStorage.setItem("user", JSON.stringify(data)); setUser(data); } } catch (error) { return; } }; const userLogout = async () => { await api.post("logout/"); localStorage.removeItem("user"); setUser(null); }; const authContextData = { api, user, userLogin, userLogout, error, }; return ( <AuthContext.Provider value={authContextData}> {props.children} </AuthContext.Provider> ); }; views.py # --------------------------------------------- # # ------------------- Login ------------------- # # --------------------------------------------- # @api_view(['POST']) @permission_classes([AllowAny]) @authentication_classes([SessionAuthentication]) def user_login(request): if request.method … -
Django Template and Static folders arrangement
I know that similar topics exist but for a half of the day i haven't found a single answer which could clear my doubts. So the question is : I've just started to practice with Django 3.2. But i have an issue with loading a templates and static files from specified folders. ├───project │ ├───first_app │ ├───migrations │ ├───static │ │ └───core │ ├───templates │ │ └───core │ └───__pycache__ ├───project │ ├───static │ └───css └───templates So i want to keep some "global" templates and static files in "project_root/templates" / "project_root/static" and some specific templates/statics within an assigned app (example of path: "project_root/app_name/templates/app_name/index.html" and "project_root/app_name/static/app_name/index.css". The option to keep templates and static files within an app works just well. But when i try to render some .html file from "project_root/templates/" in view.py it doesn't work. Is it correct to store templates/statics in such a way? How to arrange the file structures to make it work? How to point django which exactly template i want to render: from an app folder or from a root folder? Thanks for any response in advance! -
Error While Changing a field From CharField to ForeignKey
models.py from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator from django.core.validators import MinValueValidator # Create your models here. class student(models.Model): username = models.ForeignKey(User, on_delete=models.CASCADE) student_name = models.CharField(max_length=100) semester = models.IntegerField(default=1, validators=[MaxValueValidator(8), MinValueValidator(1)]) stream = models.CharField(max_length=50) address = models.CharField(max_length=200) date_of_birth = models.DateField(auto_now=False, auto_now_add=False) roll_number = models.CharField(max_length=20) This is the model I have also registered the model in admin.py and in settings.py. When I am trying to see the student table it hits me with this error, after changing the username coloumn from CharField to ForeignKey, When I change back to Charfield the problem gets fixed. I cleared all the data using python manage.py flush. Then used makemigration and migrate. But the problem exists still. -
Django redirecting to home after login does not work
I am trying to redirect to homepage after login with no sucess settings.py LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', home, name='home'), path('defaultsite', home, name='home'), ] views.py def home(request): return render(request, 'general/index.html') ] I do not have a personalized Django login system (usying system default) but nothing seems to work. Changing LOGIN_REDIRECT_URL = 'home' to LOGIN_REDIRECT_URL = '/' does not work either. Strangely, LOGOUT_REDIRECT_URL = 'home' works like a charm. Any help? Using Django 4.1.7 & python 3.10.5 -
Is it possible to mock SimpleUploadedFile?
I have a function like this: def my_func(): [...] with open(full_path, "rb") as file: image.image = SimpleUploadedFile( name=image.external_url, content=file.read(), content_type="image/jpeg", ) image.save() print(f"{file_name} - Saved!") I would like mock the "SimpleUploadedFile" for a test (calling print...). Is it possible? A little bit of context: the function download and upload files. Maybe the test is not necessary... -
How to update articles in Python Django?
I made a blog using Django. I watched a lot of videos to make a function that the user can update/edit own articles. But I did not get it work. I'm new in Django, so if anyone can help me, I would be thankful. Here is my views.py: from django.shortcuts import render, redirect from .models import Article from django.http import HttpResponse from django.contrib.auth.decorators import login_required from . import forms #from django.core.paginator import Paginator from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger @login_required(login_url="/accounts/login/") def article_list(request): articles = Article.objects.all().order_by('-date') paginator = Paginator(Article.objects.all().order_by('-date'), 6) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) index = items.number - 1 max_index = len(paginator.page_range) page_range = paginator.page_range[0:max_index] return render(request, 'articles/article_list.html', {'articles':articles, 'items':items, 'page_range':page_range}) @login_required(login_url="/accounts/login/") def article_details(request, slug): article = Article.objects.get(slug=slug) return render(request, 'articles/article_details.html', {'article':article}) @login_required(login_url="/accounts/login/") def article_create(request): if request.method == 'POST': form = forms.CreateArticle(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() return redirect('articles:list') else: form = forms.CreateArticle() return render(request, 'articles/article_create.html', {'form':form}) @login_required(login_url="/accounts/login/") def article_edit(request, slug): article = Article.objects.get(slug=slug) form = forms.CreateArticle(request.GET, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() return redirect('articles:list') return render(request, 'articles/article_edit.html', {'form':form}) I was trying to do the view in article_edit. Here … -
Django Session works in localhost but not in remote server
I have set a session value during my login view upon successful user authentication. However, this session value is returning None in another view while i am trying to access it(The same code works in my local environment) login_view @csrf_excempt @api_view(['POST']) def login_view(request): # Authenticate user - upon success authentication request.session['username'] = username request.session['password'] = password # Able to print the stored session value here as well print(request.session.get('username')) **Redirect to landing.html** Once the user is authenticated and the landing page is loaded upon session check. def index(request): print("the session value is : ", request.session.get('username')) #this returns None if request.session.get('username') return render(request, 'landing.html') # if session present, render the landing.html page else: return render(request, 'auth.html') #if session not present, reload the login page again what am i missing here? I tried a lot to debug, but to no avail. while running in my local environment, i can see the cookies in the browser while i inspect the page, but it is not the case while i run it over my apache server. Also, i am using file based sessions and i have set the SESSION_ENGINE and SESSION_FILE_PATH accordingly. I also tried looking at similar questions already being asked on the same, … -
When QuerySet is evaluated when get_queryset is overridden
Have not understand very well how QS is evaluated when overriden. Based on leedjango question, we are able to override get_queryset in a view class. In this same example, I have not been able to understand when the get_queryset method is returning the QS evaluated. We know how QS are evaluated in general, as it is explained in eugene question. For instance, I have the following components: Front End sending GET request to the appropriate URL: //Dashboard.js: export default function Dashboard() { const [tableData, setTableData] = useState([]); const getUserSchools = () => { getUser({ email: keycloak.email }).then((response) => { const { data: users } = response; if (users.length) { const appUser = users[0]; axios .get(`/api/school/list/?user_id=${appUser.id}`) .then((data) => { setTableData(data.data.results); }) .catch((err) => { /* eslint-disable-next-line */ console.error(err); setTableData([]); }); } }); }; Then, it hits the school-urls.py looking for which view is related to that URL: urlpatterns = [ url(r"^list/$", SchoolsList.as_view()), ] SchoolsList is the appropriate View which is overriding get_queryset and returns the queryset: #list.py class LargeResultsSetPagination(pagination.PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' max_page_size = 100 class SchoolsList(generics.ListAPIView): pagination_class = LargeResultsSetPagination serializer_class = SchoolGetSerializer def get_queryset(self): queryset = School.objects.all() user_id = self.request.query_params.get('user_id', None) if (user_id is not None): queryset …