【问题标题】:Variables and attributes may not begin with underscores in django templatedjango 模板中的变量和属性不能以下划线开头
【发布时间】:2018-06-10 19:27:30
【问题描述】:

在这种情况下创建一个私有过滤器可以正常工作:

   {{ 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

【问题讨论】:

  • ...不要使用下划线?
  • 你能发布你得到的完整错误吗?你在哪里检索_id,你可以将它设置为一个新的变量,比如id_to_display,这样模板就不会打架了吗?
  • 谢谢,但在这种情况下不是一个选项,因为我使用的是 couchdb
  • 你试过了吗:{% private='_id' as myNewID %} 然后{% url 'value.show' myNewID %} ?
  • @register.simple_tag def underscoreTag(obj, attribute): obj = dict(obj) return obj.get(attribute) 感谢“Chiheb Nexus”,我也使用了你的提议。 {% underscoreTag value "_id" as id %}

标签: python django django-templates django-template-filters


【解决方案1】:

只是为了让@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 对象有效负载。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    • 2010-09-07
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多