Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setting `CategoryInline.extra` at the class level is now deprecated. Set `CategoryInline.factory_kwargs` instead
I use django-extra-view on my project, i want to use CreateWithInlinesView and InlineFormSetFactory but i get this error Setting `CategoryInline.extra` at the class level is now deprecated. Set `CategoryInline.factory_kwargs` instead. This is my views.py class QuestionInline(InlineFormSetFactory): model = Question ordering = ("order", "category") extra = 1 class CategoryInline(InlineFormSetFactory): model = Category extra = 0 class SurveyCreate(CreateWithInlinesView): model = Survey fields = '__all__' list_display = ("name", "is_published") inlines = [CategoryInline, QuestionInline] and this is how i call it on page.html <form action="" method="post"> {% csrf_token %} <table> {% for formset in inlines %} {{ formset }} {% endfor %} </table> <div> <input class="btn btn-primary" type="submit" value="Submit"> </div> </form> -
How to Create a Comment Model for Posts in a Django Project
I am new in creating projects using Django, so I am creating a Blog Project, I am trying to add a comment function for my posts, I have created a Class Based View for the comments. I have also tried 2 comments as a trial from the admin and they are showing perfectly. My only issue is that I can not view the form from the website. I am not sure what I have missed? Here is the models.py class Comment(models.Model): # To know Who liked user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) body = models.TextField(max_length=300) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.post}-{self.user}-Comment No.{self.pk}" Here is the views: class Comment_create(CreateView): model = Comment fields = ['body'] template_name = 'blog/post_detail.html' form_class = CommentModelForm def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) Here is the forms.py class CommentModelForm(forms.ModelForm): body = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'Add a comment...'})) class Meta: model = Comment fields = ('body',) Here is the urls.py path('blogs/comment', Comment_create.as_view(), name='comment-post'), Here is the template: <h2>Comments...</h2> {% if not post.comment_set.all %} No comments yet {% else %} {% for c in post.comment_set.all %} <div class="ui segment mb-5"> <span>{{ c.user }} {{ c.created }}</span> <div class='mt-5'>{{ c.body }}</div> </div> {% … -
How to solve page not found 404 - python django?
I have created an app which has the index.html which is the main page and when I run "py manage.py runserver" command it opens the index page. Then I created another app for home page and added urls, created views and everything as far as I know. But when I click "home" it navigates to "http://127.0.0.1:8000/static/home.html" and says "Page not found(404)" and "'home.html' could not be found" I will paste my code below webapp\settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tbs', 'tbs_home' ] webapp\urls.py: urlpatterns = [ path('', include('tbs.urls')), path('tbs_home', include('tbs_home.urls')), path('admin/', admin.site.urls) ] tbs_home\urls.py: urlpatterns = [ path('home',views.home, name='home') ] tbs_home\views.py: def home(request): return render(request, 'home.html') templates\home.html: {% extends 'index.html' %} {% load static%} {% block content%} <h1 style = "font-family:Georgia;font:40px;font-style:normal;">Hi! {{name}}</h1> <form action="add" method="POST"> {% csrf_token %} Enter 1st num : <input type="text" name="num1"><br> Enter 2nd num : <input type="text" name="num2"><br> <input type="submit"> </form> {% endblock %} templates\index.html: This is the part where "home.html" link is given in "index.html" page <div class="col-xs-10 text-right menu-1"> <ul> <li class="active"><a href="{% static 'home.html' %}">Home</a></li> I think I've provided the necessary code snippets, thank you for your help in advance. I should be able to navigate to home page … -
Best way to take a Python program that runs on a terminal and get it running on Django
I have a chess game in python that runs on a basic terminal (user vs ai) and I essentially am trying to figure out the best way to take this terminal program and have it run in a Django project. I chose Django because it was recommended to me as a python based web framework and am also using Docker which should make it easier to get get hosted on a cloud service. I looked into some basic Django tutorials but they were also pretty basic about creating views and back end work. I thought it would just be simple to just run the python code, print to the screen, and take input but it seems more difficult than that. Essentially I would just like my program to run when a user loads the page but it seems more complex than that I am stuck trying to just recreate the terminal in Django. -
TypeError Object of type 'bytes' is not JSON serializable
Code causing the error is in a view: return JsonResponse({"messages": messages}) Contents of messages is: [ { 'from_self': 0, 'item_id': '29587918269741646013775288731697152', 'item_type': 'text', 'text': b'Test', 'thread_id': '340282366841710300949128228322131625374', 'ticket': 32866, 'timestamp': datetime.datetime(2020, 10, 29, 9, 37, 43, tzinfo=<UTC>), 'user_id': '31612701168' } ] I don't understand what part of this is type bytes? Django 3 and Python 3. -
Django model field dynamic choices which calls API
Say I have the following model: class DenyList(models.Model): vm_id = models.CharField(max_length=25) I want to add choices to the vm_id field, however the choices are dynamic via API of an external virtual machine registry system. so I have that done in the following way: class MachineChoices(object): def get_vms(self): if 'makemigrations' in sys.argv or 'migrate' in sys.argv: return [] # calls api, optionally cache, return the vms def __iter__(self): yield from self.get_vms() class DenyList(models.Model): vm_id = models.CharField(max_length=25, choices=MachineChoices()) The above works that: When creating migrations it won't call the API to set all the options in the migration file It is driven from the backend so it works on all model forms so as in django admin. Django admin displays the label instead of the raw value in list display (requires caching implemented in MachineChoices for efficiency) I don't feel this is elegant as it involves hackery to deceive django especially during migrations. I am aware that an alternative is to use autocomplete libraries but I need to customize with django forms. So are there any better ways to do this? -
How to get django model permission in Djano REST API?
In Django template i use like this {% if perms.app_label.can_do_something %} <form here> {% endif %} how to achieve same in Django rest API, how serialize all permission and return through API request -
Reason for form not showing although I added it in the template
I have made a new Comment Model in my Django Project but the form is not showing in the browser although I added the form in the template. Here is the models.py class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) body = models.TextField(max_length=300) def __str__(self): return str(self.pk) Here is the views: def comment_create(request, self): post = get_object_or_404(Post, slug=self.kwargs['slug']) user = User.objects.get(user=request.user) c_form = CommentModelForm() context = { 'post': post, 'user': user, 'c_form': c_form, } return context Here is the forms.py class CommentModelForm(forms.ModelForm): body = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'Add a comment...'})) class Meta: model = Comment fields = ('body',) Here is the urls.py path('blogs/comment', comment_create, name='comment-post'), Here is the template: <form action="" method="POST"class='ui fluid form'> {% csrf_token %} <input type="hidden" name="post_id" value={{post.id}}> {{ c_form }} <button type="submit" name="submit_c_form" class="">Send</button> </form> -
DoesNotExist at /api/users Token matching query does not exist in Django rest api
I am trying this for so long but have failed everytime. I want to return the particular user associated with the token. The frontend dev will send a request with token on the header and I need to return the particular user after that user has logged in. My view: class UsersListView(ListAPIView): serializer_class = UserListSerializer def get(self, request, *args, **kwargs): user = Token.objects.get(key="token").user return self.list(request, user) and I also, tried this which returns Token matching query does not exist. class UsersListView(ListAPIView): serializer_class = UserListSerializer def get_queryset(self): return User.objects.filter(user =Token.objects.get(key="token").user) My serializer is: class UserListSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' My user model is: class UserManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): """Creating new user and saving the user.""" if not email: raise ValueError('Admin must have a valid email') user = self.model(email=self.normalize_email(email), **kwargs) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """Creates and saves a new super user""" user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user # # class User(AbstractBaseUser, PermissionsMixin): """ Custom user model that supports using email instead of username """ email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) objects = UserManager() USERNAME_FIELD = … -
Can't figure out how to Parse data from another endpoint using rest_framework
I'm trying to figure out how to parse data directly into a database in Django, i've gone through the rest_framework tutorial. But all can gather from that is, How to create an APIview which displays the data directly from the endpoint, since when i view the DB i can't see the data being stored after i have put the request through. Or i can create some kind of form to post the data through the front-end to the database, but that doesn't make any sense to do that since it would just be dataentry rather then just pulling the related keys. But i can't for the life of me figure out how to just request the data, parse it using an already existing model with the related keys and add that to a database. Feel free to destroy me for this but i really can't find anything in relation to this or maybe i just don't know the right lingo to search. -
Best way to set unique_together for all fields of a django model
I would like to prevent the creation of duplicated rows on some tables of my database. I know one way to do it is setting the unique_together or constraints attribute in the Meta class of the model as a tuple with the names of the fields, but I'd like to know if there's a better way to do it since my models have 30+ fields, so I don't think it would be practical to repeat the names of them again. The way I have it now: class MyModel(models.Model): model_id = models.BigAutoField(db_column="MyModelColumnID", primary_key=True) field1 = models.BooleanField(...) field2 = models.CharField(...) field3 = models. ... . . . field34 = models. ... class Meta: db_table = "MyTableName" unique_together = ( "field1", "field2", "field3", . . . "field34" ) I'm looking for something like unique_together="__all__" or all_unique=True, is this possible on Django? It is important to me to handle this as a database constraint, the get_or_create method won't suffice since it's for an app using multiple threads and making multiple concurrent calls to the database. Thanks ! -
Integrate PDF js web viewer in Django web application
I want to display a ".pdf" document in a Django-based Webapp using pdf-js. The reason for that is to have access to the current pdf page number as mentionned in this stack overflow exchange. I was able to use the default pdf-js viewer as described in this tutorial. However, I could not integrate it with my Django webapp. When I use a similar scheme in the Tutorial, I get the following error: The current path, web/viewer.html, didn't match any of your URL patterns. When I add the following view : def pdf_View(request): return render(request,'static_files/web/viewer.html') Using this view, the pdf is not displayed, only the buttons (next, previous page, zoom in,out ...). -
how to add element in django list
I'm confused with how django adds elements to a list. consider the following: def add(request): if request.method == "POST": form = NewTaskForm(request.POST) if form.is_valid(): task = form.cleaned_data["task"] request.session['tasks'].append(task) # request.session['tasks'] += [task] return HttpResponseRedirect(reverse("tasks:index")) else: return render(request, "tasks/add.html",{ "form": form }) return render(request, "tasks/add.html",{ "form": NewTaskForm() }) if we add a print statement after request.session['tasks'].append(task) we get a list: ['check email'] we also get the same list if we comment the append line and use the correct way with += However, on the redirect to task/index the first way shows an empty list and the second way shows the list that's expected. Why? Whats going on? -
How can I create and edit user profiles in django?
I'm trying to create a profile when a new user is created, but I'm very new to this and I'm very lost. I'm not sure if I'm even creating a profile at all, and if I am I can't figure out how to let the user edit it once it's created. Any help is appreciated. I'm not fully understanding how to link a profile to the user and I'm having a hard time understanding signals... also apologies for the terrible documentation, I haven't made anything consistent in the least forms.py class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('email',) class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('email',) class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['bio','specialty', 'style',] class EditProfileForm(ModelForm): class Meta: model = Profile fields = ('bio', 'specialty', 'style',) models.py class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class Profile(models.Model): user = models.OneToOneField('accounts.CustomUser', on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) specialty = models.CharField(max_length=150, blank=True) style = models.CharField(max_length=150, blank=True) def create_profile(sender, instance, created, **kwargs): if created: user_profile = Profile.objects.create(user=instance) post_save.connect(create_profile, sender=CustomUser) signals.py @receiver(post_save, sender=User) def save_profile(sender, instance, … -
Proxy Model Customization
I have proxy models for related types. The problem is ListView and DetailView connection. Courses has all types of course, each course must have related type's URL. Here is full structure of my sample code, ( models, views, urls, template) #models.py COURSE_TYPES = ( ('a', 'Appetizer'), ('s', 'Soup and Salad'), ('m', 'Main Course'), ('d', 'Dessert') ) class Course(models.Model): type = models.CharField(max_length=1, choices=COURSE_TYPES) name = models.CharField(max_length=100) slug = models.SlugField(blank=True, unique=True) thumbnail = models.ImageField(null=True, blank=True) description = models.TextField(max_length=1000) def get_absolute_url(self): return reverse('course', kwargs={'slug':self.slug}) class AppetizerManager(models.Manager): def get_queryset(self): return super(AppetizerManager, self).get_queryset().filter( type='a') class MainManager(models.Manager): def get_queryset(self): return super(MainManager, self).get_queryset().filter( type='m') class Appetizer(Course): objects = AppetizerManager() class Meta: proxy = True class Main(Course): objects = MainManager() class Meta: proxy = True #views.py class CourseListView(ListView): model = Course template_name = 'courses.html' class AppetizerDetailView(DetailView): model = Appetizer template_name = 'appetizer_detail.html' class MainDetailView(DetailView): model = Main template_name = 'main_detail.html' #urls.py urlpatterns = [ path('courses/', views.CourseListView.as_view(), name='courses'), path('appetizer/<slug:slug>/', views.AppetizerDetailView.as_view(), name='appetizer'), path('main/<slug:slug>/', views.MainDetailView.as_view(), name='main'), ] #courses.html <h1>Courses</h1> {% for course in object_list %} <ul> <li><a href="{{ course.get_absolute_url }}">{{ course.name }}</a></li> </ul> {% endfor %} How can I edit my code for this purpose properly? Thanks. -
Django ValueError: Need 3 values to unpack in for loop; got 2. How to unpack zipped data in template?
I was trying to display some zipped data in a table within a Django template and kept getting this error: ValueError: Need 3 values to unpack in for loop; got 2. It contains a dictionary and a list. I've tested the same code in idle and it prints out fine. What am I doing wrong? Thanks in advance! Here's what i did for Django: views.py labels = [1, 4, 5] mydic = {'a': ['a','b','c'], 'b':['e','f','g'], 'c':['l','m','n']} dic_items = mydic.items() zipped = zip(dic_items, labels) base.html <table> {% for (k, v), l in zipped %} <tr> <th>Label{{ l }}</th> <td>{{ v.0 }}</td> <td>{{ v.1 }}</td> <td>{{ v.2 }}</td> </tr> {% endfor %} </table> In idle with the same code it prints out: a ['a', 'b', 'c'] 1 b ['e', 'f', 'g'] 4 c ['l', 'm', 'n'] 5 I've also tried: {% for k, v, l in zipped %}; {% for k, v in dic_items %}{% for l in labels %}; {% for k,v in dic_items, for l in labels %}, etc. None of them worked. I suspect it might have something to do with the label doesn't contain the same amount of items as v? But it is the same amount as … -
How can I remove the blue glow arround the fields?
Right now i am just trying to remove some king of blue borders which appears when we start writing something in the field. As shown in image, I want to remove that blue glow. and as you can see in the image there is an image input also , i want to change that in image icon, How can i change that in a image icon instead of browse.. button Inside form.py I defined the fields classes : class Meta: model = Blog fields = ('tag',"title","image_data","body",) widgets ={ 'title' : forms.TextInput(attrs={'class':'blogtitle'}), 'body': forms.Textarea(attrs={'class':'editable medium-editor-textarea blogbody'}), 'image_data': forms.FileInput(attrs={'class':'blogimage'}) } custom.css .blogtitle:focus{ font-size:40px; text-align: left; border-top: 0px; border-right: 0px; border-left: 0px; border-bottom-style: groove; outline:none; } .blogimage{ style:fa fa-image; } If more information or code is require than tell me in comments session I will update my question with that information. -
Using Ajax to automate Like button with refreshing the page
I am trying to add Ajax to my like button to avoid refreshing everytime along with updating the count automatically as well but it is not working properly and the page keeps refreshing for some reason: So when I was trying to debug my code in Google Chrome Console Log I keep receving this error: 127.0.0.1/:96 Uncaught ReferenceError: $ is not defined and DevTools failed to load SourceMap: Could not load content for chrome-extension://gannpgaobkkhmpomoijebaigcapoeebl/bundle.min.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME for some reason. I am not an expert in JS but I am trying to understand what is happening here. So my template for the like button here it is: <form action="{% url 'blog:like-post' %}" method="POST" class="like-form" id="{{post.id}}"> {% csrf_token %} <input type="hidden" name="post_id" value='{{post.id}}'> <button type="submit" class="like-btn{{post.id}}"> {% if user not in post.liked.all %} Like {% else %} Unlike {% endif %} </button> <div class="like-count{{post.id}}">{{ post.num_likes }} Likes</div> </form> Here is the Script <script> $( document ).ready(function() { let display = false $('.like-form').submit(function(e){ e.preventDefault() const post_id = $(this).attr('id') const likeText = $(`.like-btn${post_id}`).text() const trim = $.trim(likeText) const url = $(this).attr('action') let res; const likes = $(`.like-count${post_id}`).text() const trimCount = parseInt(likes) $.ajax({ type: 'POST', url: url, data: { 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), … -
Why swagger documentation doesn't work on PythonAnywhere domain?
I have used swagger to document my APIs on the Django rest framework, and deploy it on Pythonanywhere. but the documentation URL doesn't have any response. it is my urls.py code for swagger: from drf_yasg.views import get_schema_view from drf_yasg import openapi schema_view = get_schema_view( openapi.Info( title="BoardGame API", default_version='v1', description="Test description", terms_of_service="http://****.pythonanywhere.com/", contact=openapi.Contact(email="contact@boardgame.local"), license=openapi.License(name="TEST License"), ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ ... path('', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), ] and my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'drf_yasg', 'rest_framework_swagger', 'rest_framework_simplejwt', 'django_extensions', ... ] -
How to get Django Admin reset password functionality?
When I enter the login view, I see the username & pasword fields and the only button available is "Login". How come there is no "forgot your password?" here? I've looked everywhere and can't find anything to satisfy this. Is it that there is no such functionality in Django? (which would surprise me a lot) I've already read about Authentication Views, but I'm pretty sure this is not it. Also, when I access /accounts/login it prompts the error TemplateDoesNotExist at /accounts/login. Do I really have to implement this? Are there no defaults? -
django-bootstrap-modal-form workaround for FileField required
I am using the django-bootstrap-modal-form package and there currently is an open bug for FileField where it cannot be set to required on the Model or Form level, else the form does not process. I have not seen any updates as to when this will be fixed, however it is a pretty important feature to have a file upload required as a field in a form. Can anyone help to provide me with a workaround for this in the view on form_valid or post? passing error back to modal to notify user of required field? views.py # Create class FileUploadCreateView(BSModalCreateView): template_name = 'fileupload/create-file.html' form_class = FileUploadModelForm success_message = 'Success: File was uploaded.' success_url = reverse_lazy('files_list') # Validate FileUpload field is not null # Until FileField bug fixed with django-modal-forms blank=False # Add required fields prior to posting form def form_valid(self, form): file_upload = form.cleaned_data['file_upload'] if file_upload == None: form.add_error(None, "File is required.") return super().form_valid(form) else: self.instance = form.save(commit=False) self.instance.file_upload = form.cleaned_data['file_upload'] self.instance.my_user = self.request.user self.instance.file_status = 'ready' return super().form_valid(form) template <form method="post" action="" enctype="multipart/form-data"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" style="color:#7a7a7a;"> <i class="fas fa-plus-square fa-med pr-2 align-middle"></i> <span class="align-middle">ADD File</span> </h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> … -
Django _set.all in template with one to many relationship
I am trying to output a web page with many blog posts, each of them potentially containing many images. Models.py: class FreeImage(models.Model): f_img = models.ImageField(null=True, blank=True, upload_to="img/f") f_img_alt = models.CharField(max_length=100, blank=True, null=True) post = models.ForeignKey('Post', on_delete=models.SET_NULL, null=True) class Post(models.Model): title = models.CharField(max_length=100, unique=True) Views.py: def home_view(request): posts = Post.objects.order_by('-id') freeimgs = FreeImage.objects.filter(post__in=posts) context = { 'posts':posts, 'freeimgs' :freeimgs,} return render(request, 'home.html', context) Template: {% extends 'base.html' %} {% block main %} {% for post in posts%} <h3>{{post.title}}</h3> {% for i in freeimgs.post_set.all %} <h5>Test</h5> <img src="{{ freeimage.f_img.url }}" alt="{{freeimage.f_img_alt}}"> {% endfor %} {% endfor %} {% endblock %} freeimgs.post_set.all does not return anything here. I have no idea how else I could show the images corresponding to the right post inside template. -
How return ObjectId instead of ID from Django REST Serializer?
Django REST Serializer return int id not ObjectId _id: api_views.py urls.py models.py serializers.py Return int 27, not a ObjectId: My requirements.txt Django==2.2.17 sqlparse==0.2.4 djongo==1.3.1 djangorestframework==3.12.2 rest-meets-djongo==0.0.13 -
Is this use of select_related() beneficial?
In Django's documentation, there is the following example. >>> b = Blog.objects.get(pk=1) # Update all the headlines belonging to this Blog. >>> Entry.objects.select_related().filter(blog=b).update(headline='Everything is the same') And the example is based on the following definitions of models. from django.db import models class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=200) email = models.EmailField() def __str__(self): return self.name class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() mod_date = models.DateField() authors = models.ManyToManyField(Author) number_of_comments = models.IntegerField() number_of_pingbacks = models.IntegerField() rating = models.IntegerField() def __str__(self): return self.headline What is the benefit of having select_related() in the line of Entry.objects.select_related().filter(blog=b).update(headline='Everything is the same') ? I don't see any benefit of having select_related() in the update statement. In fact, I think Entry.objects.filter(blog=b).update(headline='Everything is the same') has a better performance for it doesn't perform an unneeded inner join and doesn't populate the unneeded Blog objects. What do you think? -
Django Rest Framework - Search by query within a particular category of books
in my Django Rest Framework project, I have the following simple model: class Book(models.Model): book_title = models.CharField(max_length=100, blank=False) book_category = models.CharField(max_length=50, blank=False) Now, the user should be able to search for a title within a certain category. Therefore, I use the built-in SearchFilter provided by Django Rest Framework: class SearchBooks(generics.ListAPIView): serializer_class = BookSerializer filter_backends = [filters.SearchFilter] search_fields = ['book_title'] def get_queryset(self): return Book.objects.filter(book_category=self.request.data.get('category')) So, what I want is that the user should type the book title as search query but Django should only search within a certain category. What I do in PostMan: I pass the book title as search query and put the category into the Body section as form-data. For example, let's say I have two Book instances: Book(book_title="My Happy Days", book_category="Horror") Book(book_title="My Happy Days", book_category="Lifestyle") When I type http://127.0.0.1:8000/books/searchBooks?search=My Happy Days with category=Horror in the Body section of the PostMan application as form-data, then I should get only the 1st Book instance. But with the view you have seen above, I get both instances no matter what the category is. With my current solution, it seems that Django only focuses on the search query and that what I implemented in the get_queryset() method is not computed. How …