Django自定义包含标签 [英] Django Custom Inclusion Tags

查看:121
本文介绍了Django自定义包含标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试建立自己的模板标签。
我不知道为什么我得到这些错误。我正在跟踪Django文档。



这是我的应用程序的文件结构:

  pollquiz / 
__init__.py
show_pollquiz.html
showpollquiz.py

这是showpollquiz.py:

 从django导入模板
从pollquiz.models import PollQuiz ,Choice
register = template.Library()

@ register.inclusion_tag('show_pollquiz.html')
def show_poll():
poll = Choice.objects .all()
return {'poll':poll}

html文件: p>

 < ul> 
{poll for poll in poll
< li> {{poll.pollquiz}}< / li>
{%endfor
< / ul>我的base.html文件中的

包含如下

  {%load showpollquiz%} 

{%poll_quiz%}

然后我得到错误:

 异常值:渲染时异常:show_pollquiz.html 

我不知道为什么会这样。有任何想法吗?请记住,我还是Django的新用户

解决方案

应该不是所有的自定义过滤器都在模板目录中? p>

  templatetags / 
__init__.py
showpollquiz.py
/ pre>

然后

  @ register.inclusion_tag('show_pollquiz。 html')

在MY_TEMPLATE_DIR / show_pollquiz.html中查找模板


I'm trying to build my own template tags. I have no idea why I getting these errors. I'm following the Django doc's.

This is my app's file structure:

pollquiz/
    __init__.py
    show_pollquiz.html
    showpollquiz.py

This is showpollquiz.py:

from django import template
from pollquiz.models import PollQuiz, Choice
register = template.Library()

@register.inclusion_tag('show_pollquiz.html')
def show_poll():
    poll = Choice.objects.all()
    return { 'poll' : poll }

html file:

<ul>
{% for poll in poll 
    <li>{{ poll.pollquiz }}</li>
{% endfor 
</ul>

in my base.html file im am including like this

{% load showpollquiz %}
and
{% poll_quiz %}

Bu then I get the the error:

Exception Value: Caught an exception while rendering: show_pollquiz.html

I have no idea why this happens. Any ideas? Please keep in mind I'm still new at Django

解决方案

Shouldn't all custom filters be inside the templatetags directory?

templatetags/
    __init__.py
    showpollquiz.py

then

@register.inclusion_tag('show_pollquiz.html')

looks in MY_TEMPLATE_DIR/show_pollquiz.html for the template

这篇关于Django自定义包含标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆