Friday, April 9, 2010

Django Forms: Widgets That Could Use Examples( RadioSelect, SelectDateWidget, CheckboxSelectMultiple)

In trying to use django built-in forms, I stumbled through a few of the built-ins wishing that there had been better documentation.

Here's my attempt to help others looking into using RadioSelect, CheckboxSelectMultiple, or the SelectDateWidget.

These are all excellent features and the more I use Django, the more I like it. Chalk up Forms as another part of django that blows away any other web framework I've worked with.


from django.forms.fields import ChoiceField
from django.forms.fields import MultipleChoiceField
from django.forms.widgets import RadioSelect
from django.forms.widgets import CheckboxSelectMultiple
from django.forms.extras.widgets import SelectDateWidget

YEAR_CHOICES = ('2010','2009')
RADIO_CHOICES = [['1','Radio 1'],['2','Radio 2']]
CHECKBOX_CHOICES = (('1','The first choice'),('2','The Second Choice'))
class SimpleForm(forms.Form):
radio = forms.ChoiceField( widget=RadioSelect(), choices=RADIO_CHOICES)
date = forms.DateField(widget=SelectDateWidget(None,YEAR_CHOICES) )
checkboxes = forms.MultipleChoiceField( required=False,
widget=CheckboxSelectMultiple(), choices=CHECKBOX_CHOICES)

7 comments:

  1. This was *exactly* what I was looking for. Thanks.

    ReplyDelete
  2. As above. Why is this *ESSENTIAL* information not in the django docs?!? Madness!!!

    ReplyDelete
  3. This has just saved me from the biggest headache ever.

    ReplyDelete
  4. You should import with a " ," it easier .

    from django.forms.fields import
    ChoiceField,MultipleChoiceField

    ReplyDelete
  5. Thanks! This was incredibly helpful.

    ReplyDelete
  6. Thanks so much! This is what I want

    ReplyDelete
  7. This was what I needed exactly

    ReplyDelete