> Newforms has a spiffy way to dynamically set the "initial" values of
> fields, in the view code when the Form is constructed.
> choosecolorform = ChooseColorForm(initial={'color': 'black'})
>
> I was hoping it would be just as easy to dynamically define the
> choices available in a ChoiceField, too... but no such luck.
One of the easiest ways is probably to override __init__ in your Form
subclass and pass in the list of Colors you want to have as choices -
I don't know what your Color model looks like, so I'm assuming id and
name fields.
It's important to call super(...).__init__ to get your fields set up
in self.fields before you try to modify them.
class ChooseColorForm(forms.Form):
color = forms.ChoiceField(label='Choose a color')
def __init__(colors, *args, **kwargs):
super(ChooseColorForm, self).__init__(*args, **kwargs)
self.fields['color'].choices = [('unpainted', 'Don\'t paint it')] +
[(color.id, color.name) for color in colors]
Usage::
>>> colors = Color.objects.all()
>>> form = ChooseColorForm(colors)
Jonathan.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---