Creating a search feature
- This episode covers :-
1) How to create a simple search feature.
2) How to work with GET parameters.
- Setup :-
Terminal
cp -fr 18-Tags-ManyToMany 20-Search
cd 20-Search
source ../venv/bin/activate
- Adding a search form :-
Edit base.html file and add the following <form> element at the bottom of the <nav> element:
base/templates/base/base.html
<nav>
..
<form action="/" method="get" class="form-inline mt-2 m\
t-md-0">
<input id="q" name="q" value="{{ request.GET.q }}" \
class="form-control mr-sm-2" type="text" placeholder="Searc\
h..." aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0\
" type="submit">Search</button>
</form>
</nav>
- Updating the index view :-
Edit the myapp views.py file and replace the contents with these lines:
myapp/views.py
from django.shortcuts import render
from myapp.models import Flower
def index(request):
q = request.GET.get('q', None)
items = ''
if q is None or q is "":
flowers = Flower.objects.all()
elif q is not None:
flowers = Flower.objects.filter(title__contains=q)
return render(request, 'myapp/index.html', {'flowers': \
flowers })
Now you can search titles by providing a q GET parameter in the URL:
http://127.0.0.1:8000/?q=aga
We are again using the same index.html template:
- In Details :-
When a user requests a page like our frontpage, Django creates an HttpRequest object. This object contains metadata about that request. This includes all GET parameters.
We can then access those parameters in HttpRequest.GET. In this case we only send one, the q parameter. This is then used in the myapp index view.
If we don’t provide the q parameter or it is an empty string, then all objects are fetched: flowers = Flower.objects.all().
If q is provided, we fetch all flowers where the title field contains the query string: Flower.objects.filter(title__contains=q).
Summary
- Bootstrap provides a generic template that you can use for the search form.
- HttpRequest object contains metadata about a request. We can act on that data inside views. Like filter items based on a GET parameter.




No comments:
Post a Comment
If you have any doubts. Please let me know.