I have a view with the following code:
@login_required
def grouping(request, project_id):
groups = {}
order = {}
# Bind parameters to variables and return a 404 if one is considered incorrect
for i in range(1, 5):
if request.GET.get('filter%i' % i, None) is not None:
try:
order[i] = int(request.GET.get('filter%i' % i, None))
except ValueError:
return projects_overview(request, 'Incorrect filter parameters passed', 404)
if order == {}:
return projects_overview(request, 'Incorrect filter parameters passed', 404)
original_properties = []
# Put all of the originally passed properties in a list
for key in order:
property = Property.objects.get(pk=order[key])
original_properties.append(property)
# Get the corresponding category and project
category = original_properties[0].category
project = Project.objects.get(pk=project_id)
objects = Object.objects.filter(project=project, type__category=category)
# Group the objects with the same property values together
for object in objects:
properties = object.property_set.all().order_by('name')
values = []
for property in properties:
if property.original_property in original_properties:
values.append(property.value)
values_json = json.dumps(values)
if groups.get(values_json) is None:
groups[values_json] = []
groups[values_json].append(object)
print(groups)
return render(request, 'dashboard/groups.html', {'groups': groups, 'project': project,
'function_create_form': ObjectForm(project_id=project_id)})
The problem is the variable groups
, which returns something like this:
{'["a", "b", "c"]': [<Object: Object 3>, <Object: Object 4>], '["q", "w", "e"]': [<Object: Object 5>]}
Now I am trying to iterate over this in my template:
{% for group in groups %}
{{ group }}
{% endfor %}
This gives me the keys, which makes sense:
["a", "b", "c"] ["q", "w", "e"]
But actually I only care about the list that is attached to the key. So I do:
{% for key, group in groups %}
{{ key }}
{{ group }}
{% endfor %}
Which gives me the following error: Need 2 values to unpack in for loop; got 15.
Need 2 values to unpack in for loop; got 15.
So I tried this, but that just gives me the key, character by character like I already expected:
{% for group in groups %}
{% for object in group %}
{{ object }}
{% endfor %}
{% endfor %}
I've never had this problem before, does it have to do with the way I've structured the dictionary?
To loop over the key-value pairs in a dictionary, use the items
method.
{% for key, group in groups.items %}
{{ key }}
{{ group }}
{% endfor %}
If you just want the values, use values
:
{% for group in groups.values %}
{{ group }}
{% endfor %}
For Python 2.x:
for key, value in groups.iteritems():
{{ key }}
{{ value }}
For Python 3.x:
for key, value in groups.items():
{{ key }}
{{ value }}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.