Opened 8 years ago

Closed 8 years ago

#3841 closed (worksforme)

ManyToMany field can be empty even if required=True

Reported by: anonymous Owned by: adrian
Component: Forms Version: master
Severity: Keywords: ManyToMany field
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:

Description

A ManyToMany field defined as required=True is not considered as empty if no choice has been selected in the form.

It seems that the only values to be considered as empty are only None and ", as defined in the file newforms/fields.py :
EMPTY_VALUES = (None, ")
Unfortunately, [] is not in this list.

Adding the value [] in the list EMPTY_VALUES seems to fix the issue, please can you confirm ?

Thanks.

Change History (2)

comment:1 Changed 8 years ago by Simon G. <dev@…>

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Triage Stage changed from Unreviewed to Accepted

comment:2 Changed 8 years ago by Gary Wilson <gary.wilson@…>

  • Resolution set to worksforme
  • Status changed from new to closed

I assume you meant MultipleChoiceField and not ManyToMany field (MultipleChoiceField is the default form field used for ManyToMany model fields). Things seem to work for me when no choice is selected in the form:

>>> forms.MultipleChoiceField(choices=(('1', 'one'), ('2', 'two')), required=True).clean(None)
Traceback (most recent call last):
...
ValidationError: [u'This field is required.']

>>> forms.MultipleChoiceField(choices=(('1', 'one'), ('2', 'two')), required=True).clean([])
Traceback (most recent call last):
...
ValidationError: [u'This field is required.']
>>> class MyForm(forms.Form):
...     name = forms.MultipleChoiceField(choices=(('1', 'one'), ('2', 'two')), required=True)
...
>>> MyForm({}).errors
{'name': [u'This field is required.']}

Please post back with some examples if you are still experiencing this problem.

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