What's the best way to make a navbar search box in Django?

I would like the search box to be embedded in the navigation bar that appears at the top of every page (for example, there is an example of what I say there at the top of this StackOverflow page).

Perhaps the nav.html might look like this:

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

      

Perhaps forms.py could contain:

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

      

With the DRY principle, I don't want view.py to look for a "request" on every page, like this:

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 you can easily program a page that will process the search query and display the results. What is the best way to fetch the search terms and direct the user to that search page (return HttpResponseRedirect ('/ results /? Query =' + query)) without removing the .GET request on every page?

+2


source to share


3 answers


Just create a search box to get a generic search URL.

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

      

Use a reverse url viewer if you don't want to redirect the url ...



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

      

If I didn't understand this question, it sounds like maybe you are thinking that forms should receive / submit to the same url that loaded the current page.

+3


source


We use Google CSE on one of our sites and it's about as easy as you can get. There are several features you can enable, but it's trivial and you get all the standard Google Goodness β„’.



0


source


  • Use a separate view as Joe Holloway suggests.
  • Harness the power of forms

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

0


source







All Articles