【问题标题】:Dictionary in django templatedjango模板中的字典
【发布时间】:2012-03-02 10:16:21
【问题描述】:

我有这样的看法:

info_dict =  [{u'Question 1': ['13365', '13344']}, {u'Question 2': ['13365']}, {u'Question 3': []}]

for key in info_dict:
    for k, v in key.items():
        profile = User.objects.filter(id__in=v, is_active=True)
    for f in profile:
        wanted_fields = ['job', 'education', 'country', 'city','district','area']
        profile_dict = {}
        for w in wanted_fields:
            profile_dict[f._meta.get_field(w).verbose_name] = getattr(f, w).name

return render_to_response('survey.html',{
    'profile_dict':profile_dict,
},context_instance=RequestContext(request))

在模板中:

<ul>
    {% for k, v in profile_dict.items %}
        <li>{{ k }} : {{ v }}</li>
    {% endfor %}
</ul>

我在模板中只有一本字典。但是 4 字典可能在这里(因为 info_dict) 观点有什么问题?

提前致谢

【问题讨论】:

    标签: django


    【解决方案1】:

    在您看来,您只创建了一个变量 (profile_dict) 来保存配置文件字典。

    for f in profile 循环的每次迭代中,您都在重新创建该变量,并用新字典覆盖它的值。因此,当您在传递给模板的上下文中包含 profile_dict 时,它会保存分配给 profile_dict 的最后一个值。

    如果你想将四个 profile_dicts 传递给模板,你可以在你的视图中这样做:

    info_dict =  [{u'Question 1': ['13365', '13344']}, {u'Question 2': ['13365']}, {u'Question 3': []}]
    
    # Create a list to hold the profile dicts
    profile_dicts = []
    
    for key in info_dict:
        for k, v in key.items():
            profile = User.objects.filter(id__in=v, is_active=True)
        for f in profile:
            wanted_fields = ['job', 'education', 'country', 'city','district','area']
            profile_dict = {}
            for w in wanted_fields:
                profile_dict[f._meta.get_field(w).verbose_name] = getattr(f, w).name
    
            # Add each profile dict to the list
            profile_dicts.append(profile_dict)
    
    # Pass the list of profile dicts to the template
    return render_to_response('survey.html',{
        'profile_dicts':profile_dicts,
    },context_instance=RequestContext(request))
    

    然后在你的模板中:

    {% for profile_dict in profile_dicts %}
    <ul>
        {% for k, v in profile_dict.items %}
            <li>{{ k }} : {{ v }}</li>
        {% endfor %}
    </ul>
    {% endfor %}
    

    【讨论】:

    • 你救了我的命。谢谢
    • @TheNone: crikey,你的老板真的严格。不客气。
    猜你喜欢
    • 1970-01-01
    • 2014-03-27
    • 1970-01-01
    • 2018-10-22
    • 2019-10-22
    • 2018-05-24
    • 2014-03-04
    • 2017-11-07
    • 2014-10-11
    相关资源
    最近更新 更多