django-haystack: how to access the spelling suggestions on the template?
-
02-10-2019 - |
Question
I'm trying django-haystack with Solr and HAYSTACK_INCLUDE_SPELLING = True
.
How do you access the spelling suggestions on the template (generated by the default SearchView
) ?
Edit: another question: Can the Spelling Suggestion find words from the database ? For example, using the default Note
model from the haystack doc, and the default SearchView
, there is no spelling suggestions when I search the word "Lorm" when the database contains a note called "Lorem ipsum". Is it normal ?
Thanks :-)
Solution
If you have the search query set in the template, you can do:
{{ sqs.spelling_suggestion }}
Look at: http://docs.haystacksearch.org/dev/searchqueryset_api.html#spelling-suggestion
for more details.
For haystack to find the spelling suggestions, the search template should include the field you are looking for. So if you search template includes {{ object.title }} you should be picking up the spelling suggestion.
Maybe you forgot to do
python manage.py update_index
after you added the lorem note.
OTHER TIPS
{{ suggestion }}
should suffice if you are using the default SearchView
.
See:
https://github.com/toastdriven/django-haystack/blob/master/haystack/views.py#L118
...to see what is available in the template context.
Hassan is correct in stating that you must update/rebuild your index and that you need the right fields in your search template.
I found that the above mentioned solutions only work if we are extending the haystack.views.SearchView
. The new generic views based SearchView i.e haystack.generic_views.SearchView
do not seem to be adding the suggestion
field to the context and we will not be able to access this context variable {{ suggestion }}
.
We will need to manually add it to the context as follows:
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
Add the view to urls.py
urlpatterns = [
path('search/', MySearchView.as_view(), name='haystack_search'),
And then in the search.html
access the context variable as {{ spell_suggestion }}
Hope this helps :)
Reference: https://django-haystack.readthedocs.io/en/v2.4.1/views_and_forms.html#upgrading