Opened 7 years ago

Closed 7 years ago

#7208 closed (duplicate)

Newforms SelectMultiple widget doesn't work with required=False and ChoiceField

Reported by: jordan+django@… Owned by: nobody
Component: Forms Version: master
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:

Description

ChoiceFields using the SelectMultiple widget fail validation when optional and the browser doesn't submit a value for it.

Firefox won't submit a value for <select> form fields. Without a value, SelectMultiple sets the value to [].

The clean() function in ChoiceField checks to see if the value is None or an empty string via EMPTY_VALUES, but not [], so it tries to lookup [] in the list of acceptable choices and fails with an invalid_choice message.

from django import newforms as forms
from django.http import QueryDict

class PostForm(forms.Form):
        text = forms.CharField()
        broken = forms.ChoiceField(widget=forms.SelectMultiple, required=False)

# Firefox won't submit a <select> form field that has no option selected
postdata = QueryDict('&text=super')
form = PostForm(postdata)
form.is_valid()
form.errors

This will output:

>>> form.is_valid()
False
>>> form.errors
{'broken': [u'Select a valid choice. That choice is not one of the available choices.']}

Change History (4)

comment:1 Changed 7 years ago by timsloan

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

I had this problem too. The SelectMultiple widget doesn't work with ChoiceField, you have to use MultipleChoiceField. The error is misleading but this is in the docs.

comment:2 Changed 7 years ago by stefan at tjarks dot de

I run into the same error today and fixed it by adding [] into EMPTY_VALUES. Can anyone tell me that this is a good approach or will I encounter site effects?

comment:3 Changed 7 years ago by stefan at tjarks dot de

forget my last post, I should read the complete ticket before submitting my comment! Sorry.

comment:4 Changed 7 years ago by mattmcc

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

Dup of #4051.

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