[django] Variables and attributes may not begin with underscores

当尝试在模板中调用以下划线开头的对象时,会报如下类似错误:

TemplateSyntaxError at /

Variables and attributes may not begin with underscores: 'user._meta.get_field('name').help_text'

解决方法就是,将调用以下划线开头的对象的操作封装到模板过滤器中。

如何创建自定义模板过滤器

在 models.py 文件所在目录新建一个 templatetags 目录:

hello/
    models.py
    templatetags/
        hello_extras.py
        __init__.py
    views.py

hello_extras.py 中保存着我们自定义的模板过滤器。

在 hello_extras.py 文件的开头需要包含如下代码:

from django import template

register = template ...
more ...