python – 在Django中捕获TemplateDoesNotExist

前端之家收集整理的这篇文章主要介绍了python – 在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

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

{% if 'profile/header.html'|template_exists %}        
  {% include 'profile/header.html' %}
{% else %}
  {% include 'common/header.html' %}
{% endif %}

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

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

这是Django的通缉行为吗?

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

解决方法

自定义标签怎么样?这并没有提供包含的全部功能,但似乎满足了问题中的需求:
@register.simple_tag(takes_context=True)
def include_fallback(context,*template_choices):
    t = django.template.loader.select_template(template_choices)
    return t.render(context)

然后在你的模板中:

{% include_fallback "profile/header.html" "common/header.html" %}

猜你在找的Python相关文章