Django Search Forms & Results Pages Django.How

Author avatar wrote on 26/05/2022

Setting up the Search results template

We make Listing model is our example

1.Create the url

in listings/

 path('search',, name='search'),

2. Create the template


3. Form Action Attribute

In the search form, we send the search queries to the results page

form action="{% url 'search' %}">

Search Choices in Dropdown Lists

If we want users to be able to make changes to the options ins this case we need to create a model for these options, but if choices list is not changeable we can create a python file and list of options to a dictionary

1. Create the file listings/

2. Import the file listings/

We want to use it in the home page so edit the file

from listings.choices import price_choices, bedroom_choices, state_choices

3. Edit the index method

Edit the same file

def index(request):
    listings =Listing.objects.order_by('-list_date').filter(is_published=True)[:3]
    context = {
        'listings' : listings,
        'state_choices' : state_choices,
        'price_choices' : price_choices,
        'bedroom_choices' : bedroom_choices,
    return render(request, 'pages/index.html', context)

4. Loop throw the list of choices in the HTML File

In the HTML file that contains the search form, templates/pages/index.html

Search Filters

1. We get all the results as they are

queryset_list =Listing.objects.order_by('-list_date')

2. We check the user inputs

  if 'keywords' in request.GET:
        keywords = request.GET['keywords']

3. If exists, we filter the list based on users inputs

if keywords: 
            queryset_list = queryset_list.filter(description__icontains=keywords)

Code Example

Query Filters

queryset_list(description__icontains=keywords) contains

queryset_list(description__contains=keywords) contains case sensative

queryset_list.filter(city__iexact=city) exact match

queryset_list.filter(city__exact=city) exact match and case sensative

queryset_list.filter(bedrooms__lte=bedrooms) less than or equal

queryset_list.filter(bedrooms__mte=bedrooms) more than or equal

Preserving Form Input

After the user hit the search button, the search inputs fields will be cleared, to avoid that you need to:

1. Send the request.GET in the context

context = {
        'listings' : queryset_list,
        'valuse' : request.GET,

2. Edit the for HTML code, input to include value="{{ values.keywords }}">

For dropdown lists values, we need to set the values selected