regroup formset
Say I have a formset that I'm passing to a template. Each form has a category
field that I'd like to sort the formset by. This is the code that I have so far:
...
{% regroup formset by category as category_formset %}
<ul>
{% for category in category_formset %}
<li>{{ categor开发者_如何转开发y.grouper }}
<ul>
{% for form in category.list %}
<li>{{ form.name.value }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
...
The thing is that the output looks like:
- Category 1
- ...
- Category 2
- ...
- Category 2
- ...
- Category 3
- ...
- Category 3
- ...
- Category 3
- ...
That is, in the correct order, but not actually collated. I've already seen the "gotcha" here and tried adding {% regroup|dictsort:"category" ... %}
, but that didn't help. Any ideas? Or is {% regroup %}
not supported on formsets at all?
Update: I can get it to correctly collate the categories if I use {% regroup formset by category.value ... %}
, but then it only displays integers (as category
is a ForeignKey
field). According to the docs it should be possible to use {% regroup formset by get_category_display ... %}
to categorize on strings, but then regroup
just returns None
.
So I did get it to work, in the end. The trick was to use {% regroup formset by instance.category as category_list %}
, which will display plaintext category names and collate the entries correctly.
精彩评论