相关疑难解决方法(0)

如何检查Django中是否存在模板?

检查Django中是否存在模板的最有效方法是什么?我正在考虑捕获TemplateDoesNotExist异常,但也许有更多的Djangoistic方法来做到这一点?

谢谢你的帮助!

python django

17
推荐指数
3
解决办法
7895
查看次数

在Django中捕获TemplateDoesNotExist

我试图在使用Django 1.4.3(使用Python 2.7.2)的项目中使用SO答案:https : //stackoverflow.com/a/6217194/493211中描述的模板标签.

我这样改编:

from django import template


register = template.Library()

@register.filter
def template_exists(template_name):
    try:
        template.loader.get_template(template_name)
        return True
    except template.TemplateDoesNotExist:
        return False
Run Code Online (Sandbox Code Playgroud)

所以我可以在另一个模板中使用它:

{% if 'profile/header.html'|template_exists %}        
  {% include 'profile/header.html' %}
{% else %}
  {% include 'common/header.html' %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

通过这种方式,我可以避免使用诸如在INSTALLED_APPS中更改我的应用程序的顺序等解决方案.

但是,它不起作用.如果模板存在,那么异常会在堆栈/控制台中引发,但它不会传播到get_template(..)(从此语句中),因此不会传播给我愚蠢的 API.因此,在渲染过程中,这会在我的脸上爆炸.我将stacktrace上传到了pastebin

这是Django的通缉行为吗?

我最终停止做愚蠢的事情.但我的问题仍然存在.

python django

5
推荐指数
1
解决办法
1553
查看次数

标签 统计

django ×2

python ×2