gpt4 book ai didi

django - django 模板中的字典

转载 作者:行者123 更新时间:2023-12-04 05:40:55 25 4
gpt4 key购买 nike

我有这样的看法:

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)
有什么问题?

提前致谢

最佳答案

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

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

如果您想将四个 profile_dicts 传递给模板,您可以在您的 View 中执行此操作:

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 %}

关于django - django 模板中的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9531517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com