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
|
#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 %}
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.