Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
webscoket fails to connect after few successful connections in react application
I am using django channels to implement real time updates to react frontend. But the problem is after few successful connections from frontend with websocket, the connection drops and gives two different kind of error in firefox (can't establish connection to ws://url) and chrome (failed to connect due to unknown reason). But the connection works for the first few times but with time this error occurs. Below is the socket connection code in client-side. export default function Comment(props) { const socket = new WebSocket(`${WEBSOCKETURLCOMMENT}${props.reqID}/`); const socketLike = new WebSocket(`${WEBSOCKETURLLIKE}${props.reqID}/`); ........... const socketOpen = () => { console.log('Socket opened', 'mrlog'); } const syncWebsocketData = (e) => { try { let recData = JSON.parse(e.data); if (recData?.c) { setComm(recData.c[props.index].comments) setLoading(false) } } catch (error) { console.log('Error to parse'); } } useEffect(() => { socket.addEventListener('open', socketOpen) socketLike.addEventListener('open', socketOpen) socketLike.addEventListener('message', syncWebsocketData) socket.addEventListener('message', syncWebsocketData) return function cleanup(){ socketLike.removeEventListener('open', socketOpen) socket.removeEventListener('open', socketOpen) socketLike.removeEventListener('message', syncWebsocketData) socket.removeEventListener('message', syncWebsocketData) socket.close() socketLike.close() } }, []) ....... It works fine at first but after some udpates it can' connect anymore. -
Django query on event list: finding most recent events
I have a django model that collects events. It looks roughly like this: class Events(models.Model): class EventType(models.TextChoices): OPEN = ... CLOSE = ... OTHER = ... READ = ... user = models.ForeignKey(User, on_delete=models.CASCADE) box = models.ForeignKey(Box, on_delete=models.CASCADE) event_timestamp = models.DateTimeField(default=django.utils.timezone.now) event_type = models.CharField(max_length=6, choices=EventType.choices) Events occur when users do things with boxes. I have four very related queries I want to do, and I'm not at all sure how to do this without resorting to SQL, which usually isn't the right solution with django. For box B and user U, is the user most recently open or closed for this box? For Box B, how many users are in an open state? For Box B, I'd like to plot day by day how many users are open, so I'd like to get a grouped array of users who opened and closed on each day. I'd like a table over all boxes of how many users are in an open state. For example, in SQL these would have forms something like this (not tested code, I'm hoping it's easier to use django's query language): -- 1 SELECT event_type FROM Events WHERE event_type in ('OPEN', 'CLOSE') AND user = U HAVING max(event_timestamp); … -
Why does COUNT(*) in my SQL query return several values? How to get one single value for total rows found?
I have a Django class getting some order data from a PostreSQL database. I need to get the number of rows found in a query. Trying to get the found rows count from the following query with COUNT(*): sql = """SELECT COUNT(*) FROM mbraindb.sysmanufacturingorders o LEFT JOIN mbraindb.sysmanufacturingorderrows r ON o.manufacturingorderID = r.manufacturingorderID AND r.Enabled <> 0 left join ( select si.salesitemid, si.externalsalesid, p.productarticlenumber, p.productname from mbarticlemanagement.syssalesitems si join mbarticlemanagement.syssalesitemproducts ip on si.salesitemid = ip.salesitemid join mbarticlemanagement.sysproducts p on ip.tableid = p.productid group by si.salesitemid, si.externalsalesid, p.productarticlenumber, p.productname ) as salesitems on r.salesitemid = salesitems.salesitemid left join ( select r.manufacturingorderid, r.quantity, p.productarticlenumber, p.productname from mbraindb.sysmanufacturingorderrows r join mbarticlemanagement.sysproducts p on r.productid = p.productid group by r.manufacturingorderrowid, r.manufacturingorderid, r.quantity, p.productarticlenumber, p.productname order by r.manufacturingorderrowid asc ) as products on o.manufacturingorderid = products.manufacturingorderid %s GROUP BY o.manufacturingorderID, o.manufacturingorderCustomer, o.manufacturingorderOrgOrderID, o.Enabled, o.manufacturingorderDate, o.manufacturingorderFinishdate, o.manufacturingorderStatus, o.manufacturingorderIdentifier, coalesce(salesitems.externalsalesid, ''), coalesce(salesitems.salesitemid, 0) ORDER BY o.manufacturingorderFinishdate ASC, o.manufacturingorderOrgOrderID ASC, o.manufacturingorderID ASC;""" % (sqlwhere) When I print the result from the query above, I get a lot of data: [RealDictRow([('count', 256)]), RealDictRow([('count', 4)]), RealDictRow([('count', 32)]), RealDictRow([('count', 2)]), RealDictRow([('count', 32)]), RealDictRow([('count', 2)]), RealDictRow([('count', 9)]), RealDictRow([('count', 1)]), RealDictRow([('count', 1)]), RealDictRow([('count', 1)]), RealDictRow([('count', 1)]), RealDictRow([('count', 4)]), RealDictRow([('count', 4)]), RealDictRow([('count', 4)]), RealDictRow([('count', … -
Django get min and max value from PostgreSQL specific ArrayField holding IntegerField(s)
I have an ArrayField in my model holding IntegerFields. I'm looking for the best way in which I can extract the smallest and the biggest integer out of this array. The Django documentation doesn't give examples of something similar and I wonder if the right way would be finding out how and if I can use aggregation function on this ArrayField or if I can cast this to normal python list of integers somehow and use the build in min, max functions? Any suggestions for performing this would be helpful. Examples even more. -
How to handle Django model objects being saved concurrently?
Given I have the following Django model: class Details(models.Model): id = models.BigAutoField(primary_key=True) data = models.TextField() more_data = models.TextField() Now I have a celery task which is Updating data field of the model and rest API calls updating more_data field. Currently I have written within celery functions as: model_obj.data = data model_obj.save() and function called from API call as: model_obj.more_data = more_data model_obj.save() Now since the both functions can execute simultaneously for given id, it is possible that data might not be saved correctly. So, if I update above functions to : model_obj.data = data model_obj.save(update_fields=[data]) and model_obj.more_data = more_data model_obj.save(update_fields=[more_data]) will it work fine ? -
Retrieve Auth Code From URL Python \ Django
Devs, Im working with the SmartSheet API and it requires me to go out and pull a authroization code to establish a token for a session. Im able to to redirect to their link, than be redirected to my app in Django with the AUTH code in the URL. Here is my setup so far. Here is my View @login_required def SmartSheetAPI(request): record = APIInformation.objects.filter(api_name="SmartSheet").first() if record == None: print('Authorization Token Doesn't Exist In DB, Fetching New Token!') return redirect("https://app.smartsheet.com/b/authorize?response_type=code&client_id={}&scope=READ_SHEETS%20WRITE_SHEETS&state=MY_STATE".format(client_id)) So If you visit the following page on my app, it checks if a auth token exists in the database, if it doesnt exist than go out to the redirect and authorize it. I get dumped back to my app with the URL code in the URL to this view. The example is this on the return http://127.0.0.1:8000/api/smartsheet/smartsheetapiauth?code=123456789&expires_in=599905&state=MY_STATE I need to extract code. def SmartSheetAPIAuth(request): return render(request, 'smartsheetapiauth.html') -
DRF - How to pass model object instance from view to my serializer data?
I'd like to append an object field to my serialized data in internal value . How can I reference that object directly? In my view, I use get_object_or_404 , I tried passing the kwargs, args to my serializer but that didn't work. serializer.py class StringArrayField(serializers.ListField): def to_representation(self, obj): obj = super().to_representation(obj) return ",".join([str(element) for element in obj]) def to_internal_value(self, data): data = data.split(",") return super().to_internal_value(data) class StockListSerializer(serializers.ModelSerializer): stock_list = StringArrayField() class Meta: model = Bucket fields = ("stock_list",) view.py class EditBucketSymbols(generics.RetrieveUpdateAPIView): permission_classes = [IsAuthenticated] serializer_class = StockListSerializer queryset = Bucket.objects.all() def get_object(self, queryset=queryset, **kwargs): item = self.kwargs.get('slug') return get_object_or_404(Bucket, slug=item) -
I have a problem connecting Django and SQL Server
Error - "django.core.exceptions.ImproperlyConfigured: 'sql_server.pyodbc' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3'" enter image description here -
Django objects.filter returning nothing but objects.get working
I have a simple Django project which is going to be used as an employment website. I want to render the logged-in user skills to their user profile by filtering. The objects.filter code wont return data but the objects.get returns the correct data. I want to iterate so .get is not suitable. Models.py class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=200, blank=True) last_name = models.CharField(max_length=200, blank=True) email = models.EmailField(max_length=200, blank=True) phone_number = models.CharField(max_length=200, blank=True) tag = models.TextField(max_length=200, blank=True) sector = models.CharField(max_length=200, blank=True) avatar = models.ImageField(default='avatar.jpg', upload_to='avatar_pics') county = models.CharField(max_length=200, blank=True) slug = models.SlugField(unique=True, blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=200, blank=True) city = models.CharField(max_length=200, blank=True) def __str__(self): return f"{self.user.username}-{self.created}" views.py @login_required def my_employee_view(request): employee = Employee.objects.get(user=request.user) skills = Skill.objects.filter(user=request.user) form = EmployeeModelForm(request.POST or None, request.FILES or None, instance=employee) confirm = False if request.method == 'POST': if form.is_valid(): form.save() confirm = True context = { 'employee': employee, 'form': form, 'confirm': confirm, 'skills': skills, } return render(request, 'account/employee.html', context) HTML <table class="table table-sm"> <tr> <th>Skill</th> <th>Level</th> <th>Years of Experience</th> </tr> {% for skill in skills %} <tr> <td>{{skills.tag}}</td> <td>{{skills.level}}</td> <td>{{skills.years_of}}</td> </tr> {% endfor %} -
How to visualize values in parent fields when adding new child in Django admin? [Django]
I have two models, GlobalRule and LocalRule. When I am adding a new LocalRule in Django admin I want to visualize the values of some of the fields in the corresponding GlobalRule object. The user needs this information in order to define the local rule. Is there a way for me to display the value of global_rule.event_a, global_rule.event_b,global_rule.rule_a_b_man, global_rule.a_man, global_rule.b_man as readable but not editable fields when adding a new LocalRule in Django admin? models.py from django.db import models event_choices= ['Sales order created','PO Sent','PO created','Goods Issue','STO Packing complete','Proof of delivery','Shipment ended','Delivery (Stock Transfer)','Sales order released','Goods Receipt','Goods Issue for Stock Transfer','Invoice Receipt','Order Packing complete','Delivery created','Shipment created','Sales order item created','STO created'] # Create your models here. class GlobalRule(models.Model): event_choices_l = [(str(i), event_choices[i-1]) for i in range(1,len(event_choices))] rule_choices = [('1','No Rule'),('2','Rule'),('3','Anti-Rule')] event_a = models.CharField('Event A',max_length = 200,db_column='Event A') event_b = models.CharField('Event B',max_length = 200,db_column='Event B') rule_a_b_man = models.CharField('Manual A -> B | AnB',max_length = 200,db_column='Manual A -> B | AnB',null=True) rule_a_man = models.CharField('Manual A -> B | A',max_length = 200,db_column='Manual A -> B | A',null=True) rule_b_man = models.CharField('Manual A -> B | B',max_length = 200,db_column='Manual A -> B | B',null=True) validated = models.CharField('Validated as',max_length = 200,db_column='Validated Rule',null=True) rule_a_b_gen = models.CharField('Generated A -> B … -
Radio input type in Django forms
I am making a quiz app and I'm trying to make 4 answers to choose from but it doesn't even get rendered in html or show error so maybe you can tell me what should I fix or maybe suggest a different approach. forms: class AnswerForm(forms.Form): CHOICES = [('1', 'First Answer'), ('2', ('Second answer')), ('3', ('Third answer')), ('4', ('Fourth answer')), ] answer = forms.CharField(label='Choose the correct answer:', widget=forms.RadioSelect(choices=CHOICES)) views: def answers(request): if request.method == 'POST': form = AnswerForm(request.POST) if form.is_valid(): answer = form.cleaned_data['answer'] else: form = AnswerForm() return render(request, 'pages/questions.html', {'form': form}) html: {% block content %} {% for Questions in question_list %} <h1>{{ Questions.title }}</h1> <form method="post" action=""> {% csrf_token %} {{ form }} </form> {% endfor %} {% endblock content %} -
Django + nginx + uwsgi = 504 Gateway Time-out
Below is my configuration for Nginx, and uwsgi. uWSGI works fine, I can access it directly on port 8080 but from Nginx it is not able to access the upstream - times out with 504. I am trying to run on TLS 443. How can I solve this issue? 504 Gateway Time-out nginx/1.14.0 (Ubuntu) nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; # SSL Settings ## ssl_protocols TLSv1.2; ssl_prefer_server_ciphers on; upstream uwsgicluster { server 0.0.0.0:8080; } ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } mywebsite.com conf file server { # listen 80; # listen [::]:80; listen 443; listen [::]:443; ssl on; ssl_certificate /etc/letsencrypt/live/mywebsite.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/mywebsite.com/privkey.pem; # root /data/mywebsite.com/www; # index index.html index.htm index.nginx-debian.html; server_name mywebsite.com; location / { include uwsgi_params; uwsgi_pass uwsgicluster; # uwsgi_param UWSGI_SCRIPT django_wsgi; # 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; try_files $uri $uri/ =404; } } uwsgi ini [uwsgi] master … -
Django queryset how to get one result using slicing
I have to fetch the usernames of my authors' posts Here the code: def counter(request): authors = Post.objects.values_list('author', 'title') authors_id = Post.objects.values_list('author') authors_name = User.objects.get(id=authors_id) context = {'authors':authors, 'authors_name':authors_name} return render(request, 'account/counter.html', {'authors': authors}) Now the problem is that on 'authors_id' I have this Error: The QuerySet value for an exact lookup must be limited to one result using slicing. How can I slice the queryset's list? -
Would it be a bad idea to use Django template tags to add context to a template? (Trying to imitate ease of Vue components)
One of the problems I have with Django (at least how I've learned to use it so far) is that there's not a great way to build components like in Vue. In my templates I have been using {% include %} statements to include more modular pieces of template code/components. the problem, though, is that if I use a piece of data in the component then it needs to be passed to every single view that I use it in. For example, suppose I have this template: <p>I'm a template!</p> {% include './components/weather.html' %} and then in ./components/weather.html: <p>The weather is {{ weather.status }} today.</p> Now, in any view that I want to use weather.html in, I will need to pass in 'weather' as a context variable. It would be better if I could just include a template in another template and know that it will automatically make the database requests needed to populate the context it needs. Is there any reason I can't use a tag for this? Like instead of {{ weather.status }} use {% weather %} and then in template tags something like: @register.simple_tag def weather(): return weather.get_status() Is this going to open up some vulnerability I … -
Syntax error when writing {% load static %} when trying to load an image
Hello so im doing a little project with reactjs and django and I need to load a static image from a component, and what I'm trying to do is in the render method add {% load static %}, but it is giving me an error and I cant figure out why because I have it written in my main index.html and it gives me no errors!! Here is the code: import React, { Component } from 'react'; export default class TopBar extends Component { constructor(props) { super(props); } register(){ var x = document.getElementById("login"); var y = document.getElementById("register"); var z = document.getElementById("joinBtn"); x.style.left = "-400px"; y.style.left = "50px"; z.style.left = "110px"; } login(){ console.log('I was triggered during render') var x = document.getElementById("login"); var y = document.getElementById("register"); var z = document.getElementById("joinBtn"); x.style.left = "50px"; y.style.left = "450px"; z.style.left = "0px"; } render(){ return ( <div class="hero"> <div class="form-box"> <div class="button-box"> <div id="joinBtn"></div> <button type="button" class="toggle-btn" onClick={this.login}>Log In</button> <button type="button" class="toggle-btn" onClick={this.register}>Register</button> </div> <div class="social-icons"> {% load static %} <img src="{% static 'images/fb.png' %}" alt ="fb"/> <img src="{% static 'images/google.png' %}" alt ="gg"/> <img src="{% static 'images/tt.png' %}" alt ="tt"/> </div> <form id = "login" class="input-group"> <input type="e-mail" class="input-field" placeholder="E-mail" required/> <input type="password" … -
Using Django for communication between APIS?
I am new in the world of programming. I know a little python and i am learning Django. I understand that Django is very useful for webpages backend. But I don't just want a website or an webapp. What I want is to centralize all the operations of my company by communicating through APIS different applications such as CRM (costumer relationship management), SQL database, bulk mail software, etc. For example, I want that when I perform an action in my CRM software (sales), it activates a scrapy script that I am creating, which scrapes certain pages, and then stores information in my SQL database. Can I centralize all of this through Django as if it were a central base that connects all my scripts and the communications between APIS? -
Group By in Query Django, Sum Value for a field, by the group field
I would like to get a Query in django, grouping by a field1, and sum a field2 integer, with the register that have coincidence with field2. fields_list = Whatever.objects.filter(whatever=whatever).order_by('field1').annotate(field1).agregate(Sum(field2)) And the list that I want to get is: [ {'field1':samevaluefield1,'field2':sum(Sum of field2 with value samevaluefield1)}, {'field1':othervaluefield1,'field2':sum(Sum of field2 with value othervaluefield1)}, {'field1':other2valuefield1,'field2':sum(Sum of field2 with value other2valuefield1)} ] -
Django-CMS plugin second page
I am developing a Django-CMS plugin for my site. It should give the user the oportunity to choose between social networks on the first page(for now it's Instagram, Facebook, Twitter and Other). And after that, it should have a 'next' button, instead of a 'save' button which will lead to the second page. For example, in the second screenshot you could see how second page should look if 'Other' is choosen on the first page. First page Second page How can I implement that? -
Can you help me with my Django application, how it should start?
I need to connect to api on another server, download data (e.g. once a day) to my own server, process it and save it in another table in the database using the django rest framework. What should I do at the beginning. do you have any advice or tools that i can use? I am a beginner in this. Thank you in advance for your answer -
Django form with redirect that is callable on each page
I have a search box that can redirect the user to several pages, based on the input. When i m put the searchbox on 1 specific page called "zoek", it works fine: def zoek(request): if request.method == "POST": form = SearchForm(request.POST) if form.is_valid(): q = form.cleaned_data["SearchQuery"] for result in util.list_entries(): if q.capitalize() == result: return HttpResponseRedirect(reverse("entry", args=[result])) return HttpResponseRedirect(reverse("searchresults", args=[q])) return render(request, "encyclopedia/zoek.html", { "form": SearchForm(), }) However, I want to put this searchform in a sidebar that is included on every page. The sidebar is constructed in a base called layout.html: {% load static %} <form action="{% url 'index' %}" method="post"> {% csrf_token %} {{ searchform }} <input type="submit" value="search"> </form> But I cannot return redirects on the layout. I tried using a custom context processor, but found out those are not suited for this. How could I make sure this form functions on every page that extends layout.html? -
What can slow down an ajax call?
I know I might get slammed for this because I cannot give a case that others might duplicate. However I have a problem and being fairly new to ajax I don't know where to turn I am using ajax to fire a django GET and the django response is almost instantaneous, the ajax function takes about 2 seconds to fire views.py class NewBoard(View): @staticmethod def get(request, board_selector): context={} print('NewBoard') return JsonResponse(context, safe=False) script.js function getNewBoard(board_selector) { setWaitCursor('wait') $.ajax( { type: "GET", url: 'new-board/'+board_selector, cache: false, success: function () { console.log('x') displayBoard(); } } ); console.log('a') setWaitCursor('default') } function displayBoard() { console.log('c') } When this runs, 'NewBoard' and 'a' appear in some fast sub-second time, but 'x' and 'c' do not appear until about 2.5 seconds later. I have other similar functions that work perfectly. Maybe I am doing something fundamentally wrong, but if not where can I start to look for a way to speed this up? -
About tensorflow installation
I am working in django and tf so I have installed different libraries for my project and also now I need to install tensorflow into the same environment but when i tried doing so it raised some ereo after some search i found solution to downgrade the python to 3.7 from 3.8 but while doing so I ran into frozen problem any solution. ? -
DRF: SQL server unmanaged model with period columns
In Django, I have an unmanaged model named Client like this class Client(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=40) sys_start_time = models.DateTimeField(db_column="SysStartTime") sys_end_time = models.DateTimeField(db_column="SysEndTime") class Meta: managed = False db_table = "client" and I would like to have some basic APIs to CURD, currently using RetrieveUpdateDestroyAPIView form DRF's generic views. class GetUpdateDeleteClient(RetrieveUpdateDestroyAPIView): authentication_classes = [...] # omitted permission_classes = [...] # omitted serializer_class = ClientSerializer lookup_url_kwarg = "client_id" lookup_field = "id" I can get a client object without any problem but when I make PUT or PATCH calls to update values, an error is raised: django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot update GENERATED ALWAYS columns in table 'dbo.client'. (13537) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") Problem is that, sys_start_time & sys_end_time are period columns, and as described in MS sql doc: However, you cannot update a PERIOD column and you cannot update the history table. But I cannot figure out if there is a way to let django not send all columns when performing create and update. Goal: I would like to send GET calls to retrieve all information including these period columns, but I don't … -
Couldn't import Django
I am trying to run django from virtualenv but i am getting this error: Error Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django.core' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 17, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtu? ( when i imported django from python shell,i got this: ModuleNotFoundError: No module named 'django.core' i checked if django is installed. (welpieenv) root@li2180-35:~/welpie# source welpieenv/bin/activate (welpieenv) root@li2180-35:~/welpie# pip install django Requirement already satisfied: django in ./welpieenv/lib/python3.7/site-packages (3.1.6) Requirement already satisfied: sqlparse>=0.2.2 in ./welpieenv/lib/python3.7/site-packages (from django) (0.4.1) Requirement already satisfied: asgiref<4,>=3.2.10 in ./welpieenv/lib/python3.7/site-packages (from django) (3.3.1) Requirement already satisfied: pytz in ./welpieenv/lib/python3.7/site-packages (from django) (2021.1) (welpieenv) root@li2180-35:~/welpie# pip3 install django Requirement already satisfied: django in ./welpieenv/lib/python3.7/site-packages (3.1.6) Requirement already satisfied: sqlparse>=0.2.2 in ./welpieenv/lib/python3.7/site-packages (from django) (0.4.1) Requirement already satisfied: pytz in ./welpieenv/lib/python3.7/site-packages (from django) (2021.1) Requirement already satisfied: asgiref<4,>=3.2.10 in ./welpieenv/lib/python3.7/site-packages (from django) (3.3.1) As you guys can see virtualenv is … -
Custom filter not working in django rest framework
I made a custom filter named Productfilter and imported it to my views. It was working until a few days ago but now has stopped working totally. I tried to pass the query parameters included in the filter, but all the objects are shown as if no query parameters are included in the API endpoint. My view: class ProductAPIView(ListAPIView): permission_classes = [AllowAny] queryset = Product.objects.all() serializer_class = ProductSerializer # filter_backends = [DjangoFilterBackend] filterset_class = ProductFilter My filter: from django_filters import rest_framework as filters from ..models import * class ProductFilter(filters.FilterSet): price = filters.RangeFilter() class Meta: model = Product fields = ['price','availability', 'warranty', 'services', 'brand__id','category__id','collection__id'] My urls: path('api/products', views.ProductAPIView.as_view(), name='api-products'), My serializers: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['id', 'category','brand','collection','featured', 'best_seller','top_rated','name', 'description','picture','price','size', 'color','quantity','availability','warranty', 'services', ] # lookup_field = "slug" depth = 1