newforms and dynamic choices

276 views
Skip to first unread message

Brian Victor

unread,
Jan 13, 2007, 5:39:13 PM1/13/07
to django...@googlegroups.com
Let's say there's a Room model. And let's say there's a ManyToMany
relationship with User to specify which users can schedule certain
rooms. How should a person in such a circumstance create a SelectField
on a form with a user's rooms as choices? Or more generally, how should
I go about changing a field's parameters based on information that can't
be known until the form is instantiated?

My instinct is to override __init__ on the form to provide choices to
it, which then overrides room_field.choices. Is that right, or is there
a cleaner or more idiomatic way of doing it?

(And by the way, Adrian, thanks for the select date widget. It's
exactly what I was looking for and has served as a great model for
similar widgets.)

--
Brian

Honza Král

unread,
Jan 13, 2007, 5:57:10 PM1/13/07
to django...@googlegroups.com
On 1/13/07, Brian Victor <homeu...@brianhv.org> wrote:
>
> Let's say there's a Room model. And let's say there's a ManyToMany
> relationship with User to specify which users can schedule certain
> rooms. How should a person in such a circumstance create a SelectField
> on a form with a user's rooms as choices? Or more generally, how should
> I go about changing a field's parameters based on information that can't
> be known until the form is instantiated?
>
> My instinct is to override __init__ on the form to provide choices to
> it, which then overrides room_field.choices. Is that right, or is there
> a cleaner or more idiomatic way of doing it?

__init__ is a right place to put this in, you can either pass it to
the form as one of the parameters or you can create the field in
__init__ itself, for example:

class MyForm( forms.form ):
def __init__( self, *args, **kwargs ):
super( MyForm, self ).__init__( *args, **kwargs )
self.fields['some_choice'] = forms.ChoiceField( choices=[ (o.id,
str(o) ) for o in Model.objects.all() ] )

>
> (And by the way, Adrian, thanks for the select date widget. It's
> exactly what I was looking for and has served as a great model for
> similar widgets.)
>
> --
> Brian
>
>
> >
>


--
Honza Král
E-Mail: Honza...@gmail.com
ICQ#: 107471613
Phone: +420 606 678585

Reply all
Reply to author
Forward
0 new messages