[英]Using python dictionary in for loop
I am developing a project using django. 我正在使用Django开发一个项目。 I am using python dictionary to display data in for loop.
我正在使用python字典在for循环中显示数据。 I have set a dynamic key as per my requirement in dictionary using following code.
我已使用以下代码根据字典中的要求设置了动态密钥。
abc = {}
for user in users
abc[user] = "some dynamic data"
context = {
'contributors ': abc
}
return render(request, 'contacts.html', context)
I send above code to my template to display data for each user. 我将上述代码发送到模板中,以显示每个用户的数据。
{% for contributor in contributors %}
{% for contributor_mp in contributor %}
{{ contributor_mp }}
{% endfor %}
{% endfor %}
I could not even access my code in view as I got error when I tried to serialize my dictionary 尝试序列化字典时出现错误,我什至无法访问我的代码
error:'long' object has no attribute '_meta'
I was using below to display my abc dictionary : 我在下面使用它来显示我的abc字典:
json_data = serializers.serialize("json", abc,use_natural_foreign_keys=True)
return HttpResponse(json_data)
So I used json_data = serializers.serialize("json", abc[123],use_natural_foreign_keys=True) return HttpResponse(json_data) 所以我用json_data = serializers.serialize(“ json”,abc [123],use_natural_foreign_keys = True)返回HttpResponse(json_data)
and got something like below (a validated json): 并得到如下所示的内容(经过验证的json):
[{
"fields": {
"status": 0,
"description": "Fresh & Healthy",
"name": "Fresh & Healthy",
"public": false,
"custom_type": null,
"user": "mpowner",
"image_url":
"course_type": 1,
"type": 1
},
"model": "mealplan",
"pk": 140
}, {
"fields": {
"status": 0,
"description": "evening snacks",
"name": "evening snacks",
"public": false,
"custom_type": "health and taste",
"user": "mpowner",
"image_url":
"course_type": 1,
"type": 1
},
"model": "mealplan",
"pk": 155
}]
Now my problem is when I send this to my template I get an 现在我的问题是,当我将其发送到模板时,
error:'long' object is not iterable
As this is my first project in python and I am basically a php developer I am feeling really uncomfortable facing these kind of errors.Please help solving this and suggest some other way to use something like array ( a multi dimensional one) in python. 由于这是我的第一个python项目,而我基本上是一名php开发人员,面对这些错误我感到非常不舒服。请帮助解决此问题并提出其他在python中使用数组(多维数组)之类的方法。
To iterate a dict in django template you need to use items
: 要在Django模板中迭代字典,您需要使用
items
:
{% for contributor, dynamic_data in contributors.items %}
{{ user }} {{ dynamic_data }}
{% endfor %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.