I tried implementing a search bar in my nav bar that sends a GET request with parameters to /search
. When I type something into the search bar and hit enter it just takes me to /search/
with a 404 error.
Same if I manually type /search/?searchstring=32423
I also get a page not found.
views.py
def basic_search(request):
query = request.GET.get('searchstring')
if query:
context={"query": query}
return render(request, 'root_index.html', context)
else:
return redirect('/')
urls.py
url(r'^search/$', views.basic_search,)
in my base.html
<form class="navbar-form navbar-right" role="search" name="searchstring" action="/search/" method="get">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" id="Search">
</div>
<button type="submit" class="btn btn-default">
<span class="glyphicon glyphicon-search"></span>
</button>
</form>
Your first url pattern fails to match because it’s missing the trailing slash. Change it the regex to:
r'^search/$'
The second url pattern will never match anything, because the dollar (which matches end of string) is in the middle. You shouldn’t include the querystring in the regex, therefore you should just remove this pattern.
You have a function based view, so you should use request.GET
to access the get params, not self.request.GET
.