Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'),

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...