I have a database with documents in the style of a blog, that is, the name of the author, publication date, body text, etc.
I created a django structure to output records from a database as a result of a search. This part is fine. The problem is that I want to show sections of the main text with highlighted search terms (which is equivalent to a Google search result). This means that I cannot create a template tag with only the body_text attribute, because this text is not highlighted. I have already performed a function that receives a query and the main text as input and displays the same text with the search queries found in bold. My problem now is how to pass this result to the html template?
Using the tutorial from the Django documentation, suppose you have the following views.py:
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
and the corresponding template:
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
Now suppose you have a function in views.py:
def signal_tokens(text,query_q):
...
return new_text
What should be the best way to replace {{ question.question_text }the exit from signal_tokens? My solution was to replicate a context variable with a list of dictionaries, where each dictionary is a copy of each entry, except for the key 'question_text', where I used the result signal_tokens:
def index(request):
query_q = 'test'
latest_question_list = Question.objects.order_by('-pub_date')[:5]
new_context = []
for entry in latest_question_list:
temp_d = {}
temp_d['id'] = entry.id
temp_d['question_text'] = signal_tokens(entry.question_text,query_q)
new_context.append(temp_d)
context = {'latest_question_list': new_context}
return render(request, 'polls/index.html', context)
But the problem is that I need to copy all the records. Is there a more elegant way to solve this problem?