Writing search view for Django application
Shakhzhakhan Maxudbek

Shakhzhakhan Maxudbek @xinitd

About: System administrator, software engineer, technical blogger and open source contributor. Passionate about automation and cloud technologies.

Location:
Kazakhstan
Joined:
Nov 30, 2024

Writing search view for Django application

Publish Date: Feb 2
0 0

This tutorial shows, how to build search view for your Django application with SearchVector class.

Why SearchQuery? SearchQuery translates the terms the user provides into a search query object that the database compares to a search vector. By default, all the words the user provides are passed through the stemming algorithms, and then it looks for matches for all of the resulting terms (documentation).

Configure DATABASE dictionary for using PostgreSQL database management system in your project's settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'my_database',
        'USER': 'database_user',
        'PASSWORD': 'database_users_password',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}
Enter fullscreen mode Exit fullscreen mode

Create url for search view in urls.py:

from django.urls import path
from .views import search_view


app_name = 'core'

urlpatterns = [
    path('search/', search_view, name='search-view'),
]
Enter fullscreen mode Exit fullscreen mode

Create the view itself. In views.py:

from blog.models import Article
from django.contrib.postgres.search import SearchVector


def search_view(request):
    search_results = ''
    query = ''

    if request.method == 'POST':
        query = request.POST.get('q')
        search_results = Article.objects.annotate(search=SearchVector('title', 'content')).filter(search=query)

    context = {'search_results': search_results}
    return render(request, 'search.html', context)
Enter fullscreen mode Exit fullscreen mode

Now create template named as search.html:

{% extends 'base.html' %}
{% load static %}

<form action="{% url 'core:search' %}" method="POST" enctype="multipart/form-data" novalidate autocomplete="off">
    {% csrf_token %}
    <input type="text" name="q" id="id_q" placeholder="Your search query here:">
    <label for="id_q">Search query:</label>
    <input type="submit" value="Search">
</form>
Enter fullscreen mode Exit fullscreen mode

Comments 0 total

    Add comment