Python Django search with dropdown filter

In this Python Django tutorial, I will explain how to search with a dropdown filter in Django in simple steps.

Recently, I have been creating a website using the Django framework. And I needed a dropdown menu to search for employees on specific criteria.

Here we will see:

  • How to set up a Django project in simple steps
  • Implementing Python Django search with dropdown filter
  • How to add a dropdown menu in Django
  • Creating a function-based view to render a template
  • How to create a Model in Django
  • Add data from the Django admin interface

At the end of this article, you can also download the code for searching with a dropdown menu on the website using Django.

Python Django search with dropdown filter

Now, let us first understand what is a search box and learn step by step to add a dropdown menu to search in Django.

Django Search Box

A search box, search field, or search bar is a graphical control element seen in file managers, web browsers, and other computer programs as well as websites.

A search box allows the user to search for something specified by entering or selecting it from the dropdown menu.

How to create a dropdown menu to search in Django

Now, we will see an example related to the creation of a dropdown menu to search for employees on basis of their designation.

Read: How to setup Django project

Set up Django Project

To start a Django project, open the terminal and enter the following command. Here, DropdownSearchProject is the name of the Django Project.

django-admin startproject DropdownSearchProject

It will make a folder called DropdownSearchProject and to enter the project, type the below command in the terminal.

cd DropdownSearchProject

Create a Django app named MyApp inside this project folder, by typing the below command in the terminal.

python manage.py startapp MyApp

Add the app name to the INSTALLED_APP list located in the settings.py file, to activate this app.

python django search with dropdown search filter
Install App inside settings.py

By default, Django includes a urls.py file in the project directory to map the newly constructed app inside of it. To do so, add the below code in it.

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('MyApp.urls')),
]

To create models in Django open the models.py file inside the app directory and add the below-given code.

from django.db import models

# Create your models here.

class Employee(models.Model):
    emp_id=models.IntegerField(primary_key=True)
    name=models.CharField(max_length=150)
    gender=models.CharField(max_length=8)
    designation=models.CharField(max_length=150)
    def __str__(self):
        return self.name
    class Meta:
        db_table = 'Employee'

Here, we create a model class Employee has the following fields.

  1. The emp_id is Django IntegerField and acts as the primary key.
  2. The name is Django CharField. And there is a 150-character limit for this character field.
  3. The gender is Django CharField. And there is an 8-character limit for this character field.
  4. The designation is Django CharField. And there is a 150-character limit for this character field.

And to change the display name of the object in the Django model use the def __str__(self). It will render the item name as the name as we return the self.name. We also change the name of the model to Employee.

Register the model to the admin site so that the user can view it in the admin application. Open the admin.py file and add the below-given code.

from django.contrib import admin
from .models import Employee

# Register your models here.
admin.site.register(Employee)

Read: Python Change Django Version

Create a Python Django search with dropdown filter

In Django, the front end of the application is defined in Templates, so for this, create a subdirectory called Templates in the main project directory to store all of the project templates.

Open the settings.py file, and update the DIRS to refer to the Templates folder’s location.

how to search with a dropdown filter in Django
settings.py

Create a home.html file to add the HTML code for creating a dropdown menu to search in Django inside the Template folder.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <center>
        Search Employees using Dropdown Search
        <hr>
        <form method="POST>">
            {% csrf_token %}
            <select name="gender">
                <option selected disabled=true>--Select Gender--</option>
                <option>Male</option>
                <option>Female</option>
                <option>Other</option>
            </select>
            <select name="designation">
                <option selected disabled=true>--Select Designation--</option>
                <option>HR</option>
                <option>Team Lead</option>
                <option>Junior IT Engineer</option>
                <option>Senior IT Engineer</option>
            </select>
            <input type="submit" value="Search">
            <hr>
            <table border="1">
                <tr>
                    <th>Employee ID</th>
                    <th>Name</th>
                    <th>Gender</th>
                    <th>Designation</th>
                </tr>
                {% for result in data %}
                <tr>
                    <td>{{result.emp_id}}</td>
                    <td>{{result.name}}</td>
                    <td>{{result.gender}}</td>
                    <td>{{result.designation}}</td>
                </tr>
                {% endfor %}
            </table>

        </form>

    </center>
</body>

</html>
  • We will render the HTML file by calling the form tag using the POST method.
  • To protect the page from hacker assaults and make it possible to send the data securely, we include the csrf_token in the form element.
  • Then, we will use the select HTML tag to create a dropdown field for gender and designation filed.
  • Add a Search button to search for an employee on the basics of gender and designation selected using the dropdown field.
  • Then, we will use the table tag with border 1 to store Employee Id, Name, Gender, and Designation.
  • After this, for loop is used to fetch the data context which we pass in the render function in the views file.

Read: Python Django set timezone

Define View

To define the main logic for the application, open the views.py file and add the code given below.

from django.shortcuts import render
from MyApp.models import Employee

# Create your views here.

def dropdownsearch(request):
    if request.method=="POST":
        searchgender=request.POST.get('gender')
        searchdesignation=request.POST.get('designation')
     empsearch=Employee.objects.filter(gender=searchgender,designation=searchdesignation)

        return render(request,'home.html',{"data":empsearch})
    else:
        displayemp=Employee.objects.all()

        return render(request,'home.html',{"data":displayemp})

  • Create a view called dropdownsearch and import the Employee from the models.py file first.
  • After that, execute the if statement to determine whether the request method is POST.
    • If so, just get the gender and designation using the request.POST.get().
    • Then, we use the empsearch QuerySet with the filter method for returning gender and designation.
    • After this, we use the render function which returns the home.html file with empsearch model QuerySet objects.
  • If the request method is GET.
    • We use the displayemp QuerySet with all method for returning each object from the model.
    • After this, we use the render function which returns the home.html file with displayemp model QuerySet objects.

Now, we must map the view with the URL in order to call it, thus we must create a file called urls.py in the app directory. Include the code below in it.

from django.urls import path
from . import views

urlpatterns = [
path('', views.dropdownsearch, name='dropdownsearch'),
]

Read: Python Django vs ReactJS

Execute Django Model

To make a migration file that includes code for a model’s tabular schema type the below command in the terminal.

python manage.py makemigrations

To builds tables per the migration file’s schema, execute the below command.

python manage.py migrate

Add data from the Django admin interface

To add the employee from the Django admin interface, firstly we have to create an admin. Type below the given command for that.

python manage.py createsuperuser

Then, click on Employees under MYAPP. Click on the Add option to add the employee details and then click on the Save button.

Search using Dropdown Menu using Django
Admin Interface to add Employee

Read How to Create Search Autocomplete with Filter in Django

The following is the list of the employees.

How to create a dropdown menu to search in Django
List of all the employees

Execute Django Application

To launch a development server type the below-given command in the terminal.

python manage.py runserver

It will open, the page having details of the employees in the table format.

search using dropdown menu using python django
Employee Details

Now, I want to search for an employee having gender male and the designation Junior IT Engineer using the dropdown menu and Search button.

create a dropdown menu to search in python django
Search employees using dropdown search

It will show all the employees having gender male and the designation Junior IT Engineer.

search with a dropdown filter in python django
Gender=Male and Designation=Junior IT Engineer

This is how to search with a dropdown filter in Python Django.

Download Python Django search with dropdown filter complete code

Conclusion

With this, we have successfully created a Django web application that searches with a dropdown filter. Additionally, we have learned to use Django QuerySet with filter() and all() methods.
Additionally, we have also covered the following topics.

  • How to set up a Django project in simple steps
  • Implementing Python Django search with dropdown filter
  • How to add a dropdown menu in Django
  • Creating a function-based view to render a template
  • How to create a Model in Django
  • Add data from the Django admin interface

You may also like to read the following Python Django tutorials.