Open up base.html. The below code is the untouched form of the search box that I got from bootstrap.com.
<form class="d-flex" role="search">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-light" type="submit">Search</button>
</form>
I need to add form action and method attributes. Note that, name (q) and value are added to input element.
<form class="d-flex" role="search" action="{% url 'search' %}" method="GET">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search" name="q" value={{request.GET.q}}>
<button class="btn btn-outline-light" type="submit">Search</button>
</form>
Create a url for search
urls.py
path('search/', views.search, name='search'),
views.py
Import Q object first. Q is an object used to encapsulate a collection of keyword arguments. Using Q objects we can make complex queries with less and simple code.
I want user to be able to search movie title, movie descriptions or actors name. Query returns movie object.The first 2 queries uses Movie model directly.
The last query checks moviemodel if actorname is found, it returns the corresponding movie object.
from django.db.models import Q
def search(request):
query = request.GET.get('q')
results = Movie.objects.filter(
Q(title__icontains=query) |
Q(description__icontains=query) |
#Assume use searches for Tom, this query returns movie objects where actorname is Tom.
#moviemodel is the related name that we defined in models.py
Q(moviemodel__actorname__icontains=query)
)
return render(request, 'search.html', {'results':results})
create a template and name it as search.html
User will see a link on Movie titles,so he can click and watch that movie
{% extends 'base.html'%}
{% block title %}
<title>Serach Results</title>
{% endblock title %}
{% block content %}
{% for r in results%}
<a href= "{% url 'watchmovie' r.id %}">
{{r.title}}</a>
<br>
{{r.description}}
<hr>
{% endfor %}
{% endblock content %}
He can search by movie title
He can search by the movie description
He can search by the actor name