Andro Andro - 8 days ago 6
Python Question

Create a search bar with Django

I would like in my html template create a

search bar
which could display the QuerySet result to users.

For example, a
lastname search bar
, user is writing a lastname string, and the result is displayed from the Database.

I have this function for example from models.py :

def Research(request) :

#lastname_from_user =
search_lastname = Lastnale.objects.filter(lastname ='X') #Where X = what the user filled out in the search bar

context = {
"search_lastname" : search_lastname,
}
return render(request, 'template.html', context)


How I could ask a lastname string from the html template and replace
X
by this request in order to display the result ?

Display the result is not a problem, but take a string from users and use it is more difficult for me.

If you have an idea ?

Answer

It is a most common practice to send search parameter with GET request.

Just add to you template GET form:

<form method="GET" action="">
    <input type="text"  name="q" placeholder="Search" value="{{ request.GET.q }}">
    <input type="submit" value="Search">
 </form>

Now you can use it in view:

def my_view(request):
    query = request.GET.get('q')
    if query:
        queryset_list = queryset_list.filter(title__icontains=query)
    else :
        query_list = []
    return render(request, 'template.html', {'quesryset_list': queryset_list}