gpt4 book ai didi

Django:修改查询列表的上下文

转载 作者:行者123 更新时间:2023-12-01 01:45:40 24 4
gpt4 key购买 nike

我有一个包含博客风格文档的数据库,即作者姓名、出版日期、正文等。

我已经构建了一个 django 框架来作为搜索词的结果从数据库中输出条目。那部分没问题。问题是我想显示匹配的搜索词突出显示的正文部分(相当于谷歌搜索结果)。这意味着我无法创建仅具有 body_text 属性的模板标记,因为该文本未突出显示。我已经做了一个函数,它接收查询和正文文本作为输入,并用粗体显示找到的搜索词输出相同的文本。
我现在的问题是如何将此结果传递给 html 模板?

使用 tutorial来自 Django 文档,假设您有以下 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)

和相应的模板:
{% 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 %}

现在假设你在 views.py 中有这个函数:
def signal_tokens(text,query_q):
...
return new_text

更换 {{ question.question_text } 的最佳方法应该是什么?来自 signal_tokens 的输出?我的解决方案是使用字典列表复制上下文变量,其中每个字典都是每个条目的副本,除了 'question_text' key ,我使用的地方 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)

但问题是我需要复制所有条目。有没有更优雅的方法来解决这个问题?

最佳答案

这是 template filter 的理想用例.将您的高亮代码移动到 templatetags 目录中的一个文件中,将其注册为过滤器,然后您可以从模板中调用它:

{{ question.question_text|highlight:query_q }}

显然你需要通过 query_q模板上下文也是如此。

关于Django:修改查询列表的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49650588/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com