Regrouping forms in formsets

284 views
Skip to first unread message

Felix H.

unread,
Sep 3, 2010, 4:50:32 PM9/3/10
to django...@googlegroups.com
Hi!

I'd like to structure a formset of a given model by an attribute of the model, just as the regroup template tag would do. Therefore, I tried to apply regroup as one would outside a formset:

{% regroup formset.forms by attribute as forms_by_attribute %}
{% for group in forms_by_attribute %}
{{ group.grouper }}
{% for form in group %}
{{ form }}
{# ... #}

While this doesn't throw an error, it doesn't really work, either (instead of grouping by the attribute, django attempts to group by the attribute widget, which is, while logical, not the aim).

My question is this: Is using regroup as shown above a viable solution for the given problem at all? If so, how would you access the objects attributes? If not, is there an clean alternative? What would you suggest? (I have thought about multiple formsets, for example, or regrouping the objects themselves and 'faking' a formset in html in the template, but both of these are not really nice solutions)

I'd be very grateful for any hints on how to solve this -- your help is much appreciated.

Thanks!


-Felix
___________________________________________________________
WEB.DE DSL SOMMER-SPECIAL: Surf & Phone Flat 16.000 für
nur 19,99 €/mtl.!* http://web.de/DSL-Doppel-Flatrate/

Felix H.

unread,
Sep 4, 2010, 8:59:36 AM9/4/10
to Django users
Hi!

I just figured this one out and would like to share my solution for
posterity: Since the formset in question is a ModelFormSet (which I
forgot to mention in the above message, sorry!), the data for each
form can be accessed using "form.instance". Thus, the regroup tag
should read:

{% regroup formset.forms by instance.attribute as forms_by_attribute
%}
{# ... looping over the regrouped list, as usual ... #}

With this, the regrouping of forms works wonderfully.

I hope this helps someone, someday :-)

-Felix
Reply all
Reply to author
Forward
0 new messages