为什么';django不喜欢我的字典吗?

为什么';django不喜欢我的字典吗?,django,django-templates,Django,Django Templates,我是django的新手,正拼命想弄明白为什么我不能得到一组要渲染的dictionary对象。以下是该模板的一个片段,其中包含一些用于调试的PPrint: <ul> {% with req.requirement_id as reqid %} req.requirement_id: {{ req.requirement_id|pprint }}<br /> reqid: {{ reqid|pprint }}<br /&

我是django的新手,正拼命想弄明白为什么我不能得到一组要渲染的dictionary对象。以下是该模板的一个片段,其中包含一些用于调试的PPrint:

 <ul>
        {% with req.requirement_id as reqid %}
        req.requirement_id: {{ req.requirement_id|pprint }}<br />
        reqid: {{ reqid|pprint }}<br />
        e_quals: {{ e_quals|pprint }}<br />
        e_quals.reqid: {{ e_quals.reqid|pprint }}<br />

        {% for qual in e_quals.reqid %}
          qual.qual_type: {{ qual.qual_type }}
          {% if qual.qual_type == "self" %}
            <li>Only self-endorsements.</li>
          {% endif %}
          {% if qual.qual_type == "other" %}
            <li>No self-endoresements.</li>
          {% endif %}
          {% if qual.qual_type == "hasa" %}
            <li>Endorser must hold an active {{ qual.qual_data }} badge.</li>
          {% endif %}
        {% endfor %}
        {% endwith %}
      </ul>
    {req.REQUEST_id为REQUID%} 请求请求_id:{{req.requirement_id|pprint}}
    请求ID:{{reqid | pprint}}
    e_-quals:{{e_-quals | pprint}}
    e_quals.reqid:{{e_quals.reqid | pprint}}
    {e_quals.reqid%中的qual为%s} qual.qual_类型:{{qual.qual_类型}} {%if-qual.qual_type==“self”%}
  • 只有自我认可
  • {%endif%} {%if-qual.qual_type==“其他”%}
  • 没有自我认可
  • {%endif%} {%if qual.qual_type==“hasa”%}
  • 背书人必须持有有效的{qual.qual_data}}徽章
  • {%endif%} {%endfor%} {%endwith%}
以下是我得到的输出:

req.requirement_id: u'man_keephead'
reqid: u'man_keephead'
e_quals: {u'man_keephead': [<EndorsementQual: man_keephead_others>, <EndorsementQual: man_keephead_man>], u'man_trustself': [<EndorsementQual: man_trustself_self>], u'man_waiting': [<EndorsementQual: man_waiting_other>]}
e_quals.reqid: ''
req.requirement\u id:u'man\u keephead'
需求:你是“男人”
资格:{u'man'u keephead':[,],u'man'u trustself':[],u'man'u waiting':[]
e_quals.reqid:“”

我真的觉得——考虑到reqid和e_quals字典,e_quals.reqid应该生成对象列表。我不确定我遗漏了什么。

在Django的模板语言中,不能进行这种间接变量解析。它总是将
e_-quals.req-id
解释为
e_-quals[“req-id”]
-ie作为文本键

您需要创建一个简单的模板过滤器:

@register.filter
def dict_get(my_dict, key):
    return my_dict.get(key)


{{ e_quals|dict_get:req_id }}

好的清洁溶液@alex如果您是django的新手,那么知道将此代码放在何处可能会有所帮助-请查看,谢谢!很酷,很有帮助。最后,我做了一个自定义模板标记,并以这种方式进行了处理,但这要干净得多(我很高兴知道它为什么不起作用!)