django - Django 的模板语言不会在异常时静默失败?

标签 django django-templates

我喜欢 Django、ORM、管理员和社区。但是我不喜欢模板语言中的异常处理,就像这里记录的那样:invalid template variables .

是否有一个替代的模板变量,如果出现问题(即使在生产中)我总是会得到一个异常?

我更喜欢异常而不是“默默地忽略错误”。

最佳答案

一个解决方案是将您的模板后端更改为 jinja2(Django“本地”支持)following the documentation .

关于jinja2 django 后端如何处理undefined 变量问题的深入解释,can be found here (符号我的):

Invalid template variables

You can set various behaviors when an invalid variable is encountered in Jinja templates. Django sets Jinja with two default behaviors, one for when DEBUG=True -- a common setting in development -- and the other for when DEBUG=False -- a common setting in production.

If DEBUG=True and an invalid variable is set in a Jinja template, Jinja uses the jinja2.DebugUndefined class to process it. The jinja2.DebugUndefined class outputs the variable verbatim for rendering (e.g. if the template has the {{foo}} statement and the variable doesn't exist in the context, Jinja outputs {{foo}}, making it easier to spot an invalid variable).

If DEBUG=False and an invalid variable is set in a Jinja template, Jinja uses the jinja2.Undefined class to process it. The jinja2.Undefined class outputs a blank space in the position of the variable for rendering (e.g. if the template has the {{bar}} statement and the variable doesn't exist in the context, Jinja outputs a blank space). It's worth mentioning this last behavior aligns with the default behavior of invalid variables in Django templates.

In addition to the jinja2.DebugUndefined and jinja2.Undefined classes, Jinja also supports the jinja2.StrictUndefined class. The jinja2.StrictUndefined class is used to generate an immediate error instead of proceeding with rendering, which is helpful for quicker diagnosis of invalid variables. However, be aware this last class changes its behavior based on the DEBUG variable, it either generates a stack error with the invalid variable name (i.e. when DEBUG=True) or it generates a standard HTTP 500 error page (i.e. when DEBUG=False).

如果您想在模板上设置 StrictUndefined 选项,您可以使用以下示例 from the same source :

Listing 4-4. Generate error for invalid variables in Jinja with jinja2.StrictUndefined

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))

import jinja2

TEMPLATES = [    
    { 
        'BACKEND':'django.template.backends.jinja2.Jinja2',
        'DIRS': ['%s/jinjatemplates/'% (PROJECT_DIR),],
        'APP_DIRS': True,
        'OPTIONS': {
            'undefined':jinja2.StrictUndefined
        },
    }            
]

As you can see in Listing 4-4, we first declare import jinja2 to gain access to Jinja's classes in settings.py. Next, we declare the undefined key inside the OPTIONS parameter and assign it the Jinja class to process invalid variables. In this case, we use the jinja2.StrictUndefined class to get errors when invalid templates variables are encountered, but you could equally use any of the other two Jinja classes to handle invalid variables (i.e. jinja2.DebugUndefined or jinja2.Undefined).

最后,如果您想在 DEBUG=TrueDEBUG=False 之间有不同的行为,您可以在 TEMPLATES 中更改以下内容设置:

'OPTIONS': {
    'undefined': jinja2.DebugUndefined if DEBUG else jinja2.StrictUndefined
},

在开发中使用 jinja2 的调试选项,在生产中使用严格的选项(如问题中提到的那样引发错误)。

关于django - Django 的模板语言不会在异常时静默失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61000912/

相关文章:

python - 使用 Django haystack MultiValueField 迭代搜索结果 View 中的项目

django - 如何将模型管理员添加到 Django 管理员中的另一个应用程序部分?

django - 如何在 Django html 模板中制作日期显示的快捷方式,例如,Thursday 14/07/2022 => Thu 14/07/2022

python - 为什么 logged_out.html 没有覆盖 Django 注册?

django - 属性错误: 'user_list' object has no attribute '_ignore_model_permissions'

django - django 启动时使用 paramiko 来隧道化 MySql 端口

python - PIL - libjpeg.so.8 : cannot open shared object file: No such file or directory

python - 如何将 Django 1.7 中的查询集导出到 xls 文件?

python - Django CMS – 在同一模板中为用户和访客显示不同的内容

带有 if else 语句的 Django 模板链接