Question

In Haystack tutorial, Haystack is defined for the url:

(r'^search/', include('haystack.urls'))

Does it means haystack is available for any url that ends in /search/ ??

If so, how could I implement haystack in any url that doesn't necessary ends in /search/? For example I want to implement search capabilities at www.example.com and don't want to create www.example.com/search/

Thanks

Was it helpful?

Solution

It means, assuming this is your root urls.py that the you get the search view with any URL that starts with /search/. You can put anything you want to replace r'^search/'

Note that there is, in general, a difference in the URL where your search form appears and the URL that actually serves the results. For example, the search form could be on every page, but the search results would need to go to the view in that URLconf you mention.

So for example, to put a search box on every page you include the search form in your templates. It could be something like this

<form action="/search/" method="get">
{{ mysearchform.as_p }}
<input type="submit" value="Search"/>
</form>

This will send the query to the view bound to www.example.com/search/ which will be your results page. Then, in your URLconf you would simply put

from haystack.views import SearchView
from haystack.forms import SearchForm

...

url(r'^search/', SearchView(form_class=SearchForm))

And to get that form to behave properly (to have it retain the search term when the user gets the results page, for example) you can make a context processor that will return this form to context in all views:

from haystack.forms import SearchForm

def my_search(request):
    form = SearchForm()
    return {'mysearchform': form}

Do note that you must name the form in the context as something other than form because it is passed to every page including the admin interface and form will conflict with the admin login form (i.e. you wont be able to log in).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top