On Jul 29, 5:23 am, Carlos Daniel Ruvalcaba Valenzuela
<[email protected]> 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)

--
DR.

-- 
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.

Reply via email to