On 7/29/2010 8:56 AM, Daniel Roseman wrote:
> On Jul 29, 5:23 am, Carlos Daniel Ruvalcaba Valenzuela
> <clsdan...@gmail.com> wrote:
>> Hello list,
>>
>> I was wondering which would be the best way to handle this situation
>> with ModelChoiceFields:
>>
>> I have a form with a ModelChoiceField, the options presented in this
>> field may change at the view depending on the user, however,
>> ModelChoiceField requires the queryset to be given as a parameter when
>> defining the form, which is the best way to handle this? is there a
>> commonly used way for this? I was thinking on using a Factory method
>> like this:
>>
>> def MyForm_builder(queryset):
>>     class MyForm(forms.Form):
>>         field = forms.ModelChoiceField(queryset=queryset)
>>     return MyForm
>>
>> Any thoughts on this?
>>
>> Regards,
>> Carlos Daniel Ruvalcaba Valenzuela
> 
> You can easily override the __init__ method to change the queryset on
> form instantiation, by passing in an extra `user` keyword arg:
> 
>     def MyForm(forms.Form):
>         field =
> forms.ModelChoiceField(queryset=MyModel.objects.none())
> 
>         def __init__(self, *args, **kwargs):
>             user = kwargs.pop('user', None)
>             super(MyForm, self).__init__(*args, **kwargs)
>             self.fields['field'].queryset =
> MyModel.objects.filter(user=user)
> 
You can, but shouldn't you be calling the suplerclass's __init__() as
well do make sure any necessary initialization gets performed?

Of course there is no reason (except efficiency) that says the form has
to be constructed once, and no reason why it can't be created
dynamically depending on the user when the required view is called.

regards
 Steve

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to