首页 > 解决方案 > 自定义模板标签:将其实际放在模板中的什么位置?

问题描述

完成 Django 教程后,我尝试按照“包含标签:https ://docs.djangoproject.com/en/2.2/howto/custom-template-tags/ 部分中的说明进行操作。我不熟悉模板标签的语法,我也无法弄清楚阅读文档。

polls_extra.py :

from django import template
from django.template.loader import get_template
register = template.Library()
@register.inclusion_tag('results.html')
def show_results(poll):
    choices = poll.choice_set.all()
    return {'choices': choices}

结果.html:

<h1>{{ question.question_text }}</h1>
{% load poll_extras %}
<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>

<a href= {% show_results poll %}>Vote again?</a>

然后,当我提交投票选项时,我收到错误:

/polls/1/results/ 处的 AttributeError

“str”对象没有属性“choice_set”

它应该如何实际包含在 html 中?

标签: pythondjangodjango-templates

解决方案


推荐阅读