Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a very basic search form in Django

So I'm trying to get something very simple accomplished. I want to enter a term into my search box, and display it on the resulting page.

My HTML for the form is

<form method="get" action="/results/" class="navbar-form pull-right">
<input type="text" id="searchBox" class="input-medium search-query" name="q" placeholder="Search">
<input type="submit" class="btn" value="Search" >
</form>

The views.py looks like this:

def search(request):
    query = request.GET['q']
    t = loader.get_template('template/results.html')
    c = Context({ 'query': query,})
    return HttpResponse(t.render(c))

And finally the result template contains:

<div>You searched for: {{ query }} </div>

Here's the urls.py

urlpatterns = patterns('',
url(r'^home/$', 'search.views.home'),
url(r'^results/$', 'search.views.results'),

Nothing is showing up in the {{ query }} space.

like image 828
Xonal Avatar asked Jun 03 '13 19:06

Xonal


1 Answers

Ok so the action handling the search in your views.py is supposed to be search but as I suspected in your urls.py you don't call the search method anywhere.

Where do you execute search method?

Urls should be like this:

urlpatterns = patterns('',
url(r'^home/$', 'search.views.home'),
url(r'^results/$', 'search.views.search'),
# or at least have a url for the search view

Note the action attribute in your form

It is action="/results/". This means result view is the one who is supposed to be handling the form. You may also change this to action="/search/" and have your urls like this:

urlpatterns = patterns('',
url(r'^home/$', 'search.views.home'),
url(r'^results/$', 'search.views.results'),
url(r'^search/$', 'search.views.search'),
like image 85
Paulo Bu Avatar answered Oct 20 '22 22:10

Paulo Bu