gpt4 book ai didi

python - Django Templatetag,列表索引超出范围

转载 作者:太空宇宙 更新时间:2023-11-04 10:36:09 27 4
gpt4 key购买 nike

我有一个简单的模板标签,它返回一个随机事实。当数据库中没有事实时,我得到一个异常值列表索引超出范围。我用 try, except* 包装了查询集,并检查模板中是否有事实。你可以看到下面的代码:

事实.py

# template tag
from django import template
from facts.models import Fact
register = template.Library()


def random_fact():
try:
fact = Fact.objects.order_by('?')[0]
except Fact.DoesNotExist:
fact = None

return {'fact': fact}
register.inclusion_tag('facts/fact.html')(random_fact)

事实.html

<!-- Random Fact Start -->
<div class="panel panel-default sidebar">
<div class="panel-heading">
<h3 class="panel-title">Did you know?</h3>
</div>
<div class="panel-body">
{% if fact %}
<p class="text-left">{{ fact.fact }}</p>
<p class="text-right"><i class="fa fa-link"></i> <i><a href="{{ fact.website }}" target="_blank">{{ fact.author }}</a></i></p>
{% else %}
<p class="text-left">There are currently no studying tips!</p>
{% endif %}
</div>
</div>
<!-- Random Fact End -->

最佳答案

试试这个:

def random_fact():
fact = Fact.objects.order_by('?').first()
return {'fact': fact}

关于python - Django Templatetag,列表索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23255437/

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