Thursday, July 29, 2010

Re: ModelChoiceField Question

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)

--
DR.

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

No comments:

Post a Comment