May 2018
Beginner to intermediate
526 pages
11h 57m
English
Now, we will create a custom view to allow our users to search posts. First, we will need a search form. Edit the forms.py file of the blog application and add the following form:
class SearchForm(forms.Form): query = forms.CharField()
We will use the query field to let the users introduce search terms. Edit the views.py file of the blog application and add the following code to it:
from django.contrib.postgres.search import SearchVectorfrom .forms import EmailPostForm, CommentForm, SearchFormdef post_search(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] results = Post.objects.annotate( search=SearchVector('title', ...
Read now
Unlock full access