I have the following search query in views.py
:
class SearchView(View):
def get(self, request, *args, **kwargs):
queryset = BlogPost.
You can also use a function from django-haystack but you will need to configure the simple backend on your settings:
pipenv install django-haystack
Your settings.py
INSTALLED_APPS = (
'haystack'
)
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.simple_backend.SimpleEngine',
},
}
Create a new template filter:
@register.filter
def highlight_search(text, search):
from haystack.utils.highlighting import Highlighter
highlight = Highlighter(search, html_tag='strong', css_class='highlighted', max_length=400)
return highlight.highlight(text)
Your template will look something like this:
{{ result.htmldata|highlight_search:myquery|safe }}
The built-in safe
will render the html_tag that you choose on your implementation.
More info: https://django-haystack.readthedocs.io/en/master/highlighting.html