views:

91

answers:

3

I would like to have a search box integrated into a nav bar that appears on the top of each page (hey, there is an example of what I am talking about up there at the top of this StackOverflow page).

Perhaps the nav.html may look like:

<ul id="menu">
    <li><a href="/products"></li>
    <li><a href="/service"></li>
    <li>{{ nav_search_form.as_p }}</li>
</ul>

Perhaps forms.py may contain:

class NavSearchForm(forms.Form):
  query = forms.CharField(max_length=30, required=False)

With the DRY principle I do not want views.py to be looking for a 'query' on every page like:

def ProductsPage(request):
    search_form = NavSearchForm()
    if request.GET.has_key('query'):
        query = request.GET['query'].strip()
    # deal with 'Products' here...

def ServicePage(request):
    search_form = NavSearchForm()
    if request.GET.has_key('query'):
        query = request.GET['query'].strip()
    # deal with 'Service' here...

I have and can easily program a page that will handle the search query and show results. How do you best extract the search terms and direct the user to that search page (return HttpResponseRedirect('/results/?query=' + query)) without stripping the request.GET on every page?

+2  A: 

Just have the search form do a GET on your common search URL.

<form action="/search/" method="get">
...
</form>

Use the URL reverse lookup facility if you don't want to hardwire the URL...

<form action="{% url my-search-view %}" method="get">
...
</form>

Unless I misunderstood the question, it sounds like maybe you were thinking that forms have to get/post to the same URL that loaded the current page.

Joe Holloway
Adjust accordingly if you are using Javascript instead of a 'static' form submission.
Joe Holloway
+1. Works for POSTs too if you prefer.
Daniel Roseman
@Daniel Yep. In the case of a search, I prefer GET because the URL can be bookmarked, sent via email, etc. etc.
Joe Holloway
A: 
Peter Rowell
A: 
  1. Use separate view as Joe Holloway suggests.
  2. Use forms power

    def ProductsPage(request):
        search_form = NavSearchForm(request.GET)
        if search_form.is_valid():
            ....
    
Mike Korobov