Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Permission Denied for media files at AWS S3 with Heroku and Django
In order to let the user upgrade some images in my django project I've decided to use AWS S3 buckets. I've followed a couple of tutorials and everything seems to look fine with my media storage backend because I can see the updated files on my bucket. The problem is that the images aren't been served in the site. When I try to open it a simple XML appears showing an "Access Denied" error: <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>33BFF888CD1CA014</RequestId> <HostId>UEeWZpvsQzOoIvq9uSz7Xqo7KAFhHmsPsXxEGwxaDW6V1mM2B0EccXSMXj0NXCnbi+VlwlL9d00=</HostId> </Error> Some infos that might be useful: My IAM user is in a group with a AmazonS3FullAccess policy; I've tried to enable public access to my bucket and it didn't work; My bucket is in the us-east-2 region; I updated the bucket CORS configuration according to this heroku tutorial. Any idea on what could be causing this error? Thank you very much! -
Django API Framework - Nested Models View
I'm working on a Django API with the rest framework and i want to GET data of all child classes related to parent and also, the parent data. The only way i can do this right now is with the < depth = 1 > parameter inside the serializers. But the problem with this, is i get the parent data for every child, and i only want it once. I have two nested models, let's say: class Shop(models.Model): name = models.Charfield(max_length=50) address = models.Charfield(max_length=200) def __str__(self): return self.name class Product(models.Model) shop = models.ForeignKey('Shop', on_delete=models.CASCADE , related_name='product') name = models.Charfield(max_length=50) price = models.IntegerField(default=0) Serializers look like this: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = [ 'shop', 'pk', 'name', 'price', ] class ShopProductSerializer(serializers.ModelSerializer): product_set = ProductSerializer(many=True) class Meta: model = Shop fields = [ 'shop', 'pk', 'name', 'price', 'product_set', ] so if i add depth=1 to the ProductSerializer i get the repeated Shop Data. I've seen this problem is solved by creating a nested serializer like the second one. But then how do i addapt my API View to work with it? Right now it looks like this: class ProductListView(generics.ListAPIView): serializer_class = ProductSerializer def get_queryset(self): shop = self.kwargs['pk'] products = … -
Topic_id missing even after using get method
topic_id is missing even after using get method . I think it might be the pattern r'topics/(?P<topic_id>\d+)/$' . Heres the code and the error im gettings: urls.py: from django.urls import path , re_path from . import views urlpatterns = [ #Home page path('', views.index, name='index'), path('topics/', views.topics , name='topics'), re_path(r'topics/(?P<topic_id>\d+)/$' , views.topic , name = 'topic'), ] app_name = 'learning_logs' views.py: from django.shortcuts import render from .models import Topic # Create your views here. def index(request): return render(request , 'learning_logs/index.html') def topics(request , topic_id): topics = Topic.objects.order_by('date_added') context = {'topics':topic } return render(request , 'learning_logs/topics.html' , context) def topic(request , topic_id): topic = Topic.objects.get(id = topic_id) entries = topic.entry_set_order_by('-date_added') context = {'topic':topic , 'entries' : entries} return render(request , 'learning_logs/topic.html' , context) error: image -
Many-to-Many relationship in Django
I have the following 3 models: class Platform(models.Model): title = models.CharField(max_length=100, unique=True) class Profile(models.Model): title = models.CharField(max_length=110, unique=True) platform = models.ManyToManyField(Platform) class Register(models.Model): ... profile = models.ManyToManyField(Profile) ... My views.py def info(request): ... registers=Register.objects.all() ... for register in registers: profile= register.profile....??? I need to know the profile or profiles from a query of the Register model is possible? -
Is there a way to remove lines being added to markdown file from django textarea?
When creating an entry such as # Title This is an entry The following file is created # Title This is an entry When I update this file, more spaces are added. I want the spaces to be removed and only show when the user inputs spaces. The code snippets are not the complete files but should provide the relevant code that connects everything together. views.py class NewEntryForm(forms.Form): title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) entry = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control'})) def create(request): if request.method == "POST": print(request.POST.get('entry')) form = NewEntryForm(request.POST) if form.is_valid(): title = form.cleaned_data["title"].strip() if util.get_entry(title): return render(request, "encyclopedia/create.html", { "form": form, "exists": True, "title": title }) else: entry = form.cleaned_data["entry"] print(entry) util.save_entry(title, entry) return redirect("entry", title=title) else: return render(request, "encyclopedia/create.html", { "form": form, "exists": False }) return render(request, "encyclopedia/create.html", { "form": NewEntryForm(), "exists": False }) create.html {% block body %} <h2>New Entry</h2> <form class="entry-form" action="{% url 'create' %}" method="post"> {% csrf_token %} {{ form }} {% if exists %} <p class="alert alert-danger">Entry '{{ title }}' already exists.</p> {% endif %} <input type="submit" class="btn btn-primary mt-3"> </form> {% endblock %} utils.py def save_entry(title, content): """ Saves an encyclopedia entry, given its title and Markdown content. If an existing entry with the same title … -
Bad request (400) on Django Localhost
I have the project successfully deployed through AWS. However, I would like to make some changes and experiment on them using localhost:8000/ first before making the changes to AWS server. I set my settings.py to: ALLOWED_HOSTS = ['IP address', 'www.website.com'] to deploy it. Though, I also want to be able to run the server in my local computer so I can experiment it before showing to public. The url is (r^homepage$') When I go to localhost:8000/homepage, it gives a Bad Request (400). I tried many permutations of the urls but nothing works. -
Correctly import NestedViewSetMixins for Django
I am getting an error when I import attempt to import from rest_framework_extensions.mixins import NestedViewSetMixin the error is as follows ImportError: Could not import 'rest_framework_extensions.utils.default_object_cache_key_func' for API setting 'DEFAULT_OBJECT_CACHE_KEY_FUNC'. ImportError: cannot import name 'EmptyResultSet' from 'django.db.models.sql.datastructures' I am not sure why this is happening. I have already installed drf-extensions -
Duplicated entries full of Null for every entry in my sqlite DB table (there are exactly twice what I need), created in Django, how to fix?
Somehow I am getting doubled entries of the name field in the Site table in my sqlite DB. I suspect this is cause by my models.py file, but I can't see where I erred. See the image below for an example. The code I suspect is the problem is in the models.py file that looks like this. from django.db import models class Category(models.Model) : name = models.CharField(max_length=128,null=True) def __str__(self) : return self.name class States(models.Model) : name = models.CharField(max_length=128,null=True) def __str__(self) : return self.name class Region(models.Model) : name = models.CharField(max_length=128,null=True) def __str__(self) : return self.name class Iso(models.Model) : name = models.CharField(max_length=2,null=True) def __str__(self) : return self.name class Site(models.Model): name = models.CharField(max_length=128) year = models.IntegerField(null=True) description =models.CharField(max_length=2000,null=True) justification =models.CharField(max_length=2000,null=True) longitude =models.FloatField(max_length=20,null=True) latitude =models.FloatField(max_length=20,null=True) area_hectares =models.FloatField(max_length=20,null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE,null=True) state = models.ForeignKey(States, on_delete=models.CASCADE,null=True) region = models.ForeignKey(Region, on_delete=models.CASCADE,null=True) iso = models.ForeignKey(Iso, on_delete=models.CASCADE,null=True) def __str__(self) : return self.name The only other file that is cheifly involved in populating the table from the csv I am importing from is this file import csv # https://docs.python.org/3/library/csv.html # https://django-extensions.readthedocs.io/en/latest/runscript.html # python3 manage.py runscript csv_load from unesco.models import Site, Category, Region, States, Iso def run(): fhand = open('unesco/whc-sites-2018-clean.csv') reader = csv.reader(fhand) next(reader) # Advance past the header Site.objects.all().delete() … -
NameError: name "IntegerField" is not defined
I'm new to Django and I am receiing this error and I am not sure why. Can anyone assist me? Error message: I entered "python3 manage.py makemigrations" in the shell, please look at the hyperlink to view the Error Message -
Django differentiating between user and template condtion
Let's say you are creating a blogsite and you want to add a special feature that the author (of an article) can choose another user who can also edit that article with him. And that user (editor) can also be assigned by other users as editor and he (editor) can publish his own article as well and also choose another user as an editor of his article. And obviously everyone can see each other's blog, just that the edit button can only be accessed by the author and the editor of that article. What will be your method? I tried to create some models named Author, Editor, Blog. Now, I created an one to one relationship between user and author as well as author and editor, then created a many to many relationship between blog and editor and a many to one relationship between blog and author. Then I created a view of blogs objects and rendered it to the template and in template I put a if condition to check if the logged in user is that blog's author or editor, but this condition is not working. views.py -> def blog(request, pk): if request.user.is_authenticated: blogs = Blog.objects.get(id=pk) context = … -
How to make date range filter in Django?
i'd like to let user searching data by picked date range. MY MODEL class Expense(models.Model): class Meta: ordering = ('date', '-pk') category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=8, decimal_places=2) date = models.DateField(default=datetime.date.today, db_index=True) def __str__(self): return f'{self.date} {self.name} {self.amount}' VIEWS.PY class ExpenseListView(ListView): model = Expense # imported db model paginate_by = 5 def get_context_data(self, *, object_list=None, **kwargs): queryset = object_list if object_list is not None \ else self.object_list form = ExpenseSearchForm(self.request.GET) if form.is_valid(): name = form.cleaned_data.get('name', '').strip() if name: queryset = queryset.filter(name__icontains=name) category = form.cleaned_data['category'] if category: queryset = queryset.filter(category=category) grouping = form.cleaned_data['grouping'] if grouping: queryset = queryset.order_by('date', '-pk') return super().get_context_data( form=form, object_list=queryset, summary_per_category=summary_per_category(queryset), summary_per_year_month=summary_per_year_month(queryset), total_amount_spent=total_amount_spent(), **kwargs) I wish I could make this look & work like that (example from my app, 2 lines of html just to show you what result I want). I don't have a clue how to make it work with everything else, especially I want to include this to my ListView which already have one django form in it. Any thoughts? Maybe you could direct me somehow? Im absolutely confused after researching for whole day without any good result. -
Record AnonymousUsers informations DJANGO
Thanks for your time. Basically i'd like to know if does worth it to record each first request of that ipAddress(user) for day as an anonymous user and save his infos, like country, session period. Or wont be anything as much as Google Analytics does. to explain my self right. i'd like to know if is there anything awesome that i can do by storing each GET request. like on GoogleAds and etc. function to get ip: def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip -
Django | Error 403 39 on reCAPTCHA validation
I'm trying to use Google's reCAPTCHA v2 to protect my form. Working with React.js as frontend framework and Django as backend framework, I had no problems at the development stage. When I deploy this site the following error is reported on the servers' log: - admin [03/Sep/2020:21:13:06 +0000] "POST /send_email/ HTTP/1.1" 403 39 "https://www.example.com/contact/" "Mozilla/5.0 (X11; Ubuntu:..." I can't see where it is failing, this is the only message that I got from the server log. Here is the function that validates the reCAPTCHA: @api_view(['POST']) @permission_classes((permissions.AllowAny,)) def sendForm(request): data = JSONParser().parse(request) #Here are the form's data and the reCAPTCHA's token #Check reCaptcha SECRET_KEY = os.getenv("GOOGLE_KEY") recaptcha_response = data['token'] url = 'https://www.google.com/recaptcha/api/siteverify' payload = { 'secret': SECRET_KEY, 'response': recaptcha_response } dataGoogle = urllib.parse.urlencode(payload).encode() req = urllib.request.Request(url, data=dataGoogle, method='POST') # verify the token submitted with the form is valid response = urllib.request.urlopen(req) result = json.loads(response.read().decode()) if result['success']: ... Since it worked at the production stage, I'm quite lost. Note. I've verified the public and private keys. The last time I noticed that there were not any request in the Google Console Admin. Thank you in advance for your answers and time! -
Django live telecasting the actions being performed
I am developing Django application which will run a very big task at background. I would like to telecast the status of execution (live logs) on UI. I understand, django-background-tasks help to run background tasks. But when it is being executed, whatever the logs that system generates need to be live telecasted on UI (Like a similar way how Jenkins do when build is on progress). Help on how to achieve it. -
How do websites create the form fields for addresses? is there an API?
How are a the form inputs in websites created for addresses.. how are all the states and cities showing? my major question is, is there an API that can help provide the locations for an address form or do they usually hard code the locations on their website server? -
how to design the web page in Django html template
From the picture I am trying to explain what I want in web page. And for convenience I have gave the number to the block in picture and I have created block 3 ,4 5,6,7 in one .html file. Actually I want navber1 and navbar2 will display in every page of my project that's why I have to create one separate .html file for navbar1 and navbar2 but the problem is I'm not able to apply two navbar in one html file. I also tried with sidebar (for navbar2) but I have faced some issue Dropdown button not worked on the sidebar and When I reload the page the menu of the side bar will display fist then sidebar overwrite the menu and then visualised properly. please suggest me how to design the page for navbar1 and navbar2 in one html file -
What is a good tech stack for a small business non related with software industry
I'm about to start a business in which we are going to be sending emails to potential clients. We have a database already and we need to have our day-to-day work and accountability in sync. I have imagined having Heroku app(Django as I know) using Sendgrid and Mailchimp and store the finances in google sheets. The problem is that this doesn't feel like flowing. Could you help me get a good tech stack for the business to flow? -
Why Django Doesn't Accept A Rich Text Formatted By Tiny Powered Text area?
I am Working On A Blog Website And I Had A Simple Textarea With No Formatting Options provided to Users, So I Switched To A WYSIWYG Text Area With Text Formatting Functions And The Problem Is That The Form Is Not Accepting The Text Which I Pass To That Textarea So Here Is What My Model Look Like class Article(models.Model): title = models.CharField(max_length=300) slug = models.SlugField() body = models.TextField() date = models.DateTimeField(auto_now_add=True) article_thumbnail_image_url = models.ImageField(default='default.png',blank=True) finalImage = article_thumbnail_image_url.get_attname() author = models.ForeignKey(User, default=None, blank=True, null=True, on_delete=models.CASCADE) Here Is What My View Function Look Like: @login_required(login_url='/accounts/login') def write_article(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('/') else: form = forms.CreateArticle() return render(request, 'articles/write.html', {'form': form}) And Finally, This Is How My Html File Look Like <!DOCTYPE html> <html> <head> <title>Create An Article</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script> <script>tinymce.init({ selector:'textarea' });</script> </head> <body> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> <div class="box"> <form class="site-form" action="" name = "article" method="post" enctype="multipart/form-data"> <div> {{form}} {% csrf_token %} </div> </form> </div> <script> const titleInput = document.querySelector('input[name= … -
How can I send a post request to another API from my own application
urls.py urlpatterns = [ path('create_item/', CreateItem.as_view()), ] serializers.py class ParentReferans(serializers.Serializer): name = serializers.CharField() value = serializers.IntegerField() class ItemSerializer(serializers.Serializer): SubItem = serializers.BooleanField() Type = serializers.CharField() Name = serializers.CharField() ParentRef = ParentReferans(many=True, read_only=True) views.py class CreateItem(views.APIView): def post(self, request): response = requests.post('https://sandbox-quickbooks.api.intuit.com/v3/company/4620816365135062310/item?minorversion=4', data=request.data) serializer = ItemSerializer(data=request.data) if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I want to send post request to (https://sandbox-quickbooks.api.intuit.com/v3/company/4620816365135062310/item?minorversion=4) address. But I could not come to a conclusion about what I could do. How should I go about this problem? -
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
i am trying to execute the following code on terminal with django.core.mail send_mail send_mail('some title','some text','myemail@gmail.com',['otheremail@gmail.com']) but after execution the console is showing this error Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/adjtlikp/virtualenv/globalit-web/3.7/lib/python3.7/site-packages/django/core/mail/__init__.py", line 61, in send_mail return mail.send() File "/home/adjtlikp/virtualenv/globalit-web/3.7/lib/python3.7/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/adjtlikp/virtualenv/globalit-web/3.7/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/home/adjtlikp/virtualenv/globalit-web/3.7/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "/opt/alt/python37/lib64/python3.7/smtplib.py", line 251, in __init__ (code, msg) = self.connect(host, port) File "/opt/alt/python37/lib64/python3.7/smtplib.py", line 338, in connect (code, msg) = self.getreply() File "/opt/alt/python37/lib64/python3.7/smtplib.py", line 394, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") smtplib.SMTPServerDisconnected: Connection unexpectedly closed my settings.py EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_PASSWORD = 'mypass' EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_PORT = 465 DEFAULT_FROM_EMAIL = EMAIL_HOST_USER i tryed to change the EMAIL_PORT and the EMAIL_HOST but nothing changed the intersting is that in localhost the code work perfect but when i am using the host the errors came to me -
Django how to change value on table and keep old records same, apply changes to futures records only
In this Invoicing app, when i change the price on product table, all the previous invoices change too, any solution to keep old invoices same and make changes only on futures ones. class Product(models.Model): code = models.CharField(max_length=64, unique=True) name = models.CharField(max_length=64) price = models.DecimalField(max_digits=20, decimal_places=2) class Invoice(models.Model): date = models.DateField(default=timezone.now) client = models.ForeignKey(Client,on_delete=models.CASCADE) class InvoiceItem(models.Model): invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(max_digits=20, decimal_places=2) quantity = models.DecimalField(max_digits=20, decimal_places=2) -
Create and access url parameters django routers and class view
How do I create passed in url parameters. I have a class view... class ExampleView(viewsets.ModelViewSet): serializer_class = ExampleSerializer queryset = ExampleModel.objects.all() and my serializer looks like... class ExampleSerializer(serializers.ModelSerializer): class Meta: model = ExampleModel fields = '__all__' and my urls.py file... router = routers.DefaultRouter() router.register(r'example', views.ExampleView, 'example') urlspatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), re_path(r'^', views.FrontendAppView.as_view()), ] but what I really want is a way to pass in parameters, for instance, in my class view instead of doing ExampleModel.objects.all() I want to do something like ExampleModel.objects.get(field_name=param_value) in my urls.py do something like... router.register(r'<int:example_id>/example', views.ExampleView, 'example') being that I "pass in a parameter to my url" example_id I would like to somehow retrieve that in my class view but does not work -
Finding all names in a list that contains a substring without changing the characters
I'm doing a key-search in a list for a search system and having a little bit of trouble in the exhibition. I found that if I lowercase both, the list with all my pages titles and the key I could do a simple search. It worked. But in the end, to exhibit the searched titles as related results, I'm displaying the names lowercased, as I did it for comparing. I was wondering if there is any way that I could display the names as they were before comparing or a better way to do this search, looking for maintaining the original title. This is my search function def search(request): q = request.GET['q'] if util.get_entry(q): #redirect to the existing page calling entry() return redirect("entry", title=q) #searching for matching entries titles #getting all the entries titles in a list all_entries = util.list_entries() #lowering case of the list and the key to avoid comparision problems all_entries = [item.lower() for item in all_entries] key = q.lower() #making a new list with the matching results match_entries = [i for i in all_entries if key in i] #renders the results page passing the list of matching titles return render(request, "encyclopedia/search.html",{ 'title' : q, 'entries' : match_entries … -
How can I write a Jquery function which 'creates' or 'modifies' existing html modal
I'm trying to create a confirm delete window for users who are trying to delete the existing model from my cloud panel. So I created HTML design, but now I'm stuck with the coding part, I'm really green on Jquery and JS, so I pretty much know the logic, but I can't achieve it in code. How should it work? When the user presses on the delete button, I somehow need to pass in the information of the model the user is trying to delete and then modify the delete window content with the model information. What have I done for now? I have only designed the design (HTML code), which I'm putting down here. This is the delete window: <!-- Confirm delete --> <div class="modal fade" id="reply_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true" data-keyboard="false" data-backdrop="static"> <form method="post" action="{{request.build_absolute_uri}}"> {% csrf_token %} <div class="modal-dialog rounded" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title"> <div class="text-danger"> <i class="fas fa-exclamation-triangle"></i> Please confirm your action! </div> </h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <span class="text-center text-dark p-3 border-bottom shadow-sm" style="background-color: #ffe88a;font-size: 14px;">Warning: This action cannot be undone</b>.</span> <div class="modal-body" style="background-color: #fafafa;font-family: 'Mukta', sans-serif;"> {% if messages %} {% for message in messages %} … -
FilterSet field with ModelMultipleChoiceFilter for an intermediate model
I have following models: class ItemAddon(models.Model): name = models.CharField(max_length=127) price = models.DecimalField(blank=True, null=True, max_digits=10, decimal_places=2) class ItemAddonAreaRelation(models.Model): itemaddon = models.ForeignKey( 'ItemAddon', on_delete=models.CASCADE, help_text='Item Addon to relate', related_name='relations' ) area_id = models.ForeignKey( 'Area', on_delete=models.CASCADE ) class Area(models.Model): name = models.CharField(max_length=127) class ItemAddonsViewSet(viewsets.ModelViewSet): serializer_class = ItemAddonsSerializer search_fields = ('id', 'name') ordering_fields = ('id', 'name') filterset_class = ItemAddonFilter class ItemAddonFilter(FilterSet): area_ids = ModelMultipleChoiceFilter( method="filter_by_area_ids", widget=CSVWidget() ) I want to filter out ItemAddons based on area id. For example: GET /api/itemaddons?area_id=1,2,3 How can i put the queryset to get the above working?