Opened 6 years ago

Closed 5 years ago

Last modified 5 years ago

#15722 closed Bug (fixed)

Conditional Formset Rendering/Validation

Reported by: Mark Lavin Owned by: nobody
Component: Forms Version: 1.3
Severity: Normal Keywords:
Cc: ironfroggy@…, mmanfre@… Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

#14655 introduced formsets as iterables and defined __len__ as the number of forms. However this causes a side effect in that if there are no forms then bool returns False. Meaning if you have a condition in your template which looks for the formset in the context before rendering

{% if formset %}
{# formset rendering would go here... #}
{% endif %}

then if there are no forms this will not render. It also means that the management form will not be rendered. On POST if the formset is bound without the management form data it raises a ValidationError on __init__.

There are possible work-arounds:

1.) Override __nonzero___ on the formset to return True

2.) Change conditional statements to look for the existence of the management form instead i.e. {% if formset.management_form %}

Attachments (1)

15722.diff (1.3 KB) - added by Mark Lavin 5 years ago.
Patch for fix with test.

Download all attachments as: .zip

Change History (8)

comment:1 Changed 6 years ago by Calvin Spealman

Cc: ironfroggy@… added

comment:2 Changed 6 years ago by Michael Manfre

Cc: mmanfre@… added

comment:3 Changed 6 years ago by Luke Plant

Type: Bug

comment:4 Changed 6 years ago by Luke Plant

Severity: Normal

comment:5 Changed 6 years ago by Carl Meyer

Triage Stage: UnreviewedAccepted

I think we should override nonzero to return True. It's slightly unusual to have len(obj) == 0 and bool(obj) is True, but I think it's sensible here: len() reflecting the number of forms is useful, but a formset with no forms is not really "empty", as the management form alone is still functionally significant.

Changed 5 years ago by Mark Lavin

Attachment: 15722.diff added

Patch for fix with test.

comment:6 Changed 5 years ago by Mark Lavin

Easy pickings: unset
Has patch: set
UI/UX: unset

comment:7 Changed 5 years ago by Karen Tracey

Resolution: fixed
Status: newclosed

In [16756]:

Fixed #15722: ensure formsets evaluate to True even if they have no forms. Thanks mlavin.

Note: See TracTickets for help on using tickets.
Back to Top