How to Highlight Searched Queries in Result Page of Django Template

How to highlight searched queries in result page of Django template?

You could do this in a template filter. Something like:

@register.filter
def highlight_search(text, search):
highlighted = text.replace(search, '<span class="highlight">{}</span>'.format(search)
return mark_safe(highlighted)

Now in your template you can do:

{% load my_tags %} # wherever you put the template filter

{% for post in queryset %}
<div class="my-1">
<a class="link" href="{{ post.get_absolute_url }}">{{ post.title|highlight_search:query }}</a>
</div>
{% endfor %}

You'd need to send the search_text back with the context that renders the result page.

How to highlight searched queries in result page by using Function based views?

The problem is with browser cache, I have cleared cookies & cache, it works as expected.

search results highlighting with custom template tag

use sub method in regular expressions which will find and replace given query(repl) in given string.

syntax:

re.sub(pattern, repl, string, count=0, flags=0);

code:

def highlight(text, word):
word=word.lower()
result=re.sub(word ,"<Strong>%s</Strong>" % word,text,flags=re.IGNORECASE)
return mark_safe(result)

How do I highlight a particular word from a column inside a text using django?

Replace() has been changed to re.sub because replace() is unable to handle case insensitive words/characters.

In templatetags/filters.py:

from django import template
from django.utils.safestring import mark_safe
import re

register = template.Library()

@register.filter
def highlight(text, search):
search = re.split((" "), search)

for i in search:
highlighted = re.sub(i, '<span style="background-color: #000FF">{}</span>'.format(i), text, flags=re.IGNORECASE)
text = highlighted
return mark_safe(text)

Highlight search terms on a Django/PostgreSQL search results page

Even though Django doesn't support ts_headline feature from postgresql, You can manually apply it as a Function on a QuerySet to annotate:


We need additional function to operate with django ORM. Here is a sample for ts_headline. [original_source for this sample function is linked here]

Headline function sample:

from django.db import models
from django.contrib.postgres.search import Value, Func

class Headline(Func):
function = 'ts_headline'

def __init__(self, field, query, config=None, options=None, **extra):
expressions = [field, query]
if config:
expressions.insert(0, Value(config))
if options:
expressions.append(Value(options))
extra.setdefault('output_field', models.TextField())
super().__init__(*expressions, **extra)

Using the above function you can use it on a QuerySet to annotate

Example Model Definition

class Video(Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.CharField(max_length=128, verbose_name="Title")

Steps for getting highlighted search results on model title

  1. Filter and get the QuerySet needed to annotated
  2. Annotate using Headline function
  3. Get Values of your document

Filtering Objects

Video.objects.filter(filter_query)

filter_query is a Q() over title
filter_query = Q(title__contains=term)


Annotation with Headline data

Video.objects.filter(filter_query).annotate(title_highlight=Headline(F('title'), text_search_query))

ts_headline directly take the input from the document rather than from ts_vector, So we have to pass the information about which field it should access and what SearchQuery it should perform on it.

text_Search_query is SearchQuery Object with same input as the filter_query
text_search_query = SearchQuery(term)

Now after annotation, this queryset with include a extra field in all objects called title_highlight which would contain the result you wanted like:

these <b>loans</b> not being repaired


Get the values from the annotation field

using values_list over the QuerySet you can get the values from these annotated fields.

final code:

Video.objects.filter(filter_query).annotate(title_highlight=Headline(F('title'), text_search_query)).values_from('title','title_highlight')

Django display search results

You can create a custom template filter to add an HTML tag around the searched-for word in your post title or content. This will not be an exact solution but you should be able to adapt it:

@register.filter
@stringfilter
def highlight_search_term(text, search_term):
if search_term in text:
text.replace(search_term, '<span class="highlight">' + search_term + '</span>')
return mark_safe(text)

You can then apply this filter to your post title or content in your template with {{ post.title|highlight_search_term:search_term }}.

You will need to also pass search_term to your template context so that the filter can know what to highlight. Be careful with mark_safe() if you are applying this to user-submitted content!



Related Topics



Leave a reply



Submit