解决Django模板中不能使用下划线变量的问题

2022-03-11 00:00:00 变量 下划线 中不

在django中使用mongodb时 ,需要在template文件里调用mongodb自动生成的_id,但是django不允许模板文件里面使用下划线开头的变量,可以使用filter来解决

from django import template
register = template.Library()
def mongo_id(value):
    '''返回mongo的_id属性'''
    return value.get('_id','')
register.filter(mongo_id)

这样在template页面里面就可以这样使用
{{data|mongo_id}}
其中data的为dict类型

相关文章