Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing extra context to Django Haystack template

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?

like image 340
Randall Ma Avatar asked Jul 27 '26 00:07

Randall Ma


1 Answers

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
like image 108
shrewdbeans Avatar answered Jul 28 '26 13:07

shrewdbeans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!