Adding an "invalid" choice to a ChoiceField?

341 views
Skip to first unread message

Michael

unread,
Apr 1, 2008, 5:01:46 AM4/1/08
to Django users
When specifying the choices parameter is there a way to mark say, for
example, the first choice as invalid?

e.g.

TOPIC_CHOICES = (
('erroneous', '-- pick one --'), # <-- I would not want this
choice to count as being valid
('general', 'General enquiry'),
('bug', 'Bug report'),
('suggestion', 'Suggestion'),
)

class ContactForm(forms.Form):
topic = forms.ChoiceField(choices=TOPIC_CHOICES)

The scenario I'm trying to address is I would like to prevent users
from skipping over a particular choice field (instead of the user
blindly accepting the first value in the list).

I'm curious how you guys would address this. Thanks!

Thomas Guettler

unread,
Apr 1, 2008, 11:21:57 AM4/1/08
to django...@googlegroups.com
Michael schrieb:

> When specifying the choices parameter is there a way to mark say, for
> example, the first choice as invalid?
>
> e.g.
>
> TOPIC_CHOICES = (
> ('erroneous', '-- pick one --'), # <-- I would not want this
> choice to count as being valid
> ('general', 'General enquiry'),
> ('bug', 'Bug report'),
> ('suggestion', 'Suggestion'),
> )
>
> class ContactForm(forms.Form):
> topic = forms.ChoiceField(choices=TOPIC_CHOICES)
>
TOPIC_CHOICES=[('', '-- pick one --'), ('key1', '...'), ...]
And required=False for the ChoiceField (which is the default).

Thomas

--
Thomas Guettler, http://www.thomas-guettler.de/
E-Mail: guettli (*) thomas-guettler + de

Michael

unread,
Apr 1, 2008, 9:38:35 PM4/1/08
to Django users
> TOPIC_CHOICES=[('', '-- pick one --'), ('key1', '...'), ...]

Thanks, using an empty string for the value seems to do the trick. Is
there somewhere in the documentation that explains this behavior? I'm
not able to locate it anywhere.

> And required=False for the ChoiceField (which is the default).

Are you sure? the newforms documentation [1] seems to indicate that
required=True is the default for all Fields.

[1] http://www.djangoproject.com/documentation/newforms/#required

alex....@gmail.com

unread,
Apr 1, 2008, 9:52:17 PM4/1/08
to Django users
I assume he meant required=True, because being required is what causes
'' to not be allowed.

Thomas Guettler

unread,
Apr 2, 2008, 5:00:59 AM4/2/08
to django...@googlegroups.com
Michael schrieb:

>> TOPIC_CHOICES=[('', '-- pick one --'), ('key1', '...'), ...]
>>
>
> Thanks, using an empty string for the value seems to do the trick. Is
> there somewhere in the documentation that explains this behavior? I'm
> not able to locate it anywhere.
>
>
>> And required=False for the ChoiceField (which is the default).
>>
>
> Are you sure? the newforms documentation [1] seems to indicate that
> required=True is the default for all Fields.
>

Sorry, this was a typo. required=True is the default.

Reply all
Reply to author
Forward
0 new messages