2

Setting up a search page with Django Haystack involves putting in their URLconf snippet url(r'^search/', include('haystack.urls')). However, this means (at least from my extremely basic understanding of Django/MVC), that there is no simple way to pass extra context (i.e. an extra dictionary key/value) to be rendered onto the page.

In particular, I want to customize a search field to mirror the variable passed onto the page from a GET request:

<form method="get" action=".">
<input type="text" name="q" value="">
<!-- result html here -->
</form>

Say the parameter ?q=twitter is attached to the URL as part of a GET request; I'd like to make the value selector equal to twitter. If I had control of the view, I would likely do it something like this:

if request.method == 'GET':
    q = request.GET['q']
    return render(request, 'template.html', {'q': q})

And then use q as the value for the value selector in the HTML <input>.

Is there any way to accomplish this in a simple manner, besides editing the Haystack source?

4 Answers 4

9

You can sub-class the Haystack View to add to the context:

Create a views.py file in your search app (if you don't have one). And then make sure you import the Haystack view. Then you can create a sub-class like so:

import haystack.views

class SearchView(haystack.views.SearchView):
    """
    We subclass the base haystack view in order to add context.
    """

    def extra_context(self):
        return {
            'yourValue': yourValue,
        }

Don't forget to change the path to the view in your urls.py, from within your Search app:

from yourSite.apps.search.views import SearchView
2

Haystack already pass you the query. The template variable is called query:

<div>Your query was {{ query }}</div>

If you still need more things in the context, then you have to use the basic_search method. You have to create your view and call the basic_search. So, in views.py:

from haystack.views import basic_search

def yourview(request):
    ...
    return basic_search(request, extra_context={ 'foo': 'boo', })

There are more parameters you can set in case you want:

basic_search(request, template='search/search.html', load_all=True, form_class=ModelSearchForm, searchqueryset=None, context_class=RequestContext, extra_context=None, results_per_page=None)

Curiously, all of those can be called directly using the SearchView() from urls except for extra_context. In urls.py:

from haystack.views import SearchView
...
url(r'^$', SearchViewtemplate='path/to/your/template', load_all=True, form_class='YouForm', searchqueryset=AQuerySet, context_class=RequestContext, results_per_page=10), name='the_name_you_want')

None of the parameters are required. event

2

Accomplished this using a custom context processor:

from django.template import RequestContext
from django.http import HttpResponse

def get_search_query(request):
    search_query = request.GET.get('q', '')
    print search_query
    return {
        'search_query':search_query
    }

Then, simply call {{ search_query }} in any of your HTML templates.

0

If you are using the new SearchView based on generic_views i.e. haystack.generic_views.SearchView then you will need to move it to the get_context_data function instead of extra_context as mentioned here https://django-haystack.readthedocs.io/en/v2.4.1/views_and_forms.html#upgrading

Example: Below I'm adding the spelling suggestion to the context dictionary

from haystack.generic_views import SearchView

# Custom view.
class MySearchView(SearchView):

    template_name = 'search/search.html'
    queryset = SearchQuerySet().all()
    form_class = SearchForm  

    def get_context_data(self, *args, **kwargs):
        context = super(MySearchView, self).get_context_data(*args, **kwargs)

        # Add any additional context data we need to display in forms
        spell_suggestion = self.get_form().get_suggestion()
        context['spell_suggestion'] = spell_suggestion

        return context

This context variable can then be accessed in search.html as {{ spell_suggestion }}

Hope it helps :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.