Reputation: 8163
I have a web site on Django. I want to create a search input on every page. In some "base.html" I write new for this search input.
In views.py I add something like:
def main(request):
if request.method == 'POST':
search_string = request.POST['search_string']
result = search(search_string)
return direct_to_template(request, 'found_page.html', {'result': result})`
But I want it on EVERY page.
So, I create new function "search_function(request)" and add it to EVERY def in views.py. Or I can create a decorator and write it before EVERY def in views.py.
I don't want to do it EVERY time I add new def. But I don't know how. Need your help
Upvotes: 1
Views: 1455
Reputation: 17040
So this is what I think you want to do: display a search input form on every page (whichever applicable), and use only one views to handle the search.
<form>
element of the search whose action goes to your views done in the previous stepWhat I don't get is, do you need the search happen to be the search on the local page? (for example, search within this forum)
To get the query you can just supply the query by request.GET['q']
or request.POST['q']
or similar.
def search(request):
if 'q' in request.GET and request.GET['q']:
// do something
Unless your search (query) changes the state of the query result in the database, you don't want to use POST
. Use GET
instead.
Upvotes: 3
Reputation: 724
Set the action of the form to go to a different search view and let that one function take care of the search processing. You can have a dedicated search page and do the exact same thing for checking if the form is 'POST' or 'GET'. 'POST' is a search already done from any other previous page.
Upvotes: 0