Django模板中的变量和属性不能以下划线开头

2024-04-26 04:49:52 发布

您现在位置:Python中文网/ 问答频道 /正文

在这种情况下,创建专用筛选器可以正常工作:

   {{ value|private:'_id' }}

但在这种情况下,它不起作用:

   {% url 'value.show' value|private='_id' %}

有办法解决这个问题吗

过滤器示例: Django Templates and MongoDB _id

我将couchdb与mongo查询一起使用

TemplateSyntaxError 
Variables and attributes may not begin with underscores: 'value._id'
Request Method: GET
Exception Type: TemplateSyntaxError
Exception Value:    
Variables and attributes may not begin with underscores: 'value._id'
Python Version: 3.6.4

Tags: andidvaluewithexceptionnot情况private
1条回答
网友
1楼 · 发布于 2024-04-26 04:49:52

只是为了让@abed maatalla的答案更清楚一点。 我也遇到了同样的问题,那就是我正在查询并转换为json的API

解决方案是创建一个模板标记,该标记转换在模板标记(python文件)内django模板中无法读取的_id,然后输出一个结果,结果中不带下划线,该下划线在django模板中可用

这是一个名为tagger.py的模板标记文件

from django import template

register = template.Library()

@register.simple_tag
def underscoreTag(obj, attribute):
    obj = dict(obj)
    return obj.get(attribute)

然后在django html模板中

{% load tagger %}
<td> {% underscoreTag order "_id" as id %} {{ id }} </td>

请注意order是我从包含_id键的API接收的json对象有效负载

相关问题 更多 >