tags:

views:

81

answers:

2

I have a form like this:

class MyForm(forms.Form):
[...]

which is rendered in my view:

if request.method == 'GET':
    form = MyForm(request.GET)

Now, i want to add a form field which contains a set of values in a select-field, and the queryset must be filtered by the currently logged in user. So I changed the method signature so that it contains the request-object:

class MyForm(forms.Form):
    def __init__(self, user, *args, **kwargs):
         super(MyForm, self).__init__(*args, **kwargs)
         self.myfield  = forms.ChoiceField([('%s' % d.id, '%s' % d.name) for d in MyModel.objects.filter(owners = user)])

but all I get after rendering the form is an object-reference as string instead of the select-widget. I seems that a form field, once declared, can not be modified.

Any ideas?

+2  A: 

Replace your last line of code with this:

self.fields['myfield'].choices = [('%s' % d.id, '%s' % d.name) for d in MyModel.objects.filter(owners = user)]
piquadrat
A: 

I think here's what you're after:

class MyForm(forms.Form):
    def __init__(self, user, *args, **kwargs):
         super(MyForm, self).__init__(*args, **kwargs)
         self.fields['myfield']  = forms.ModelChoiceField(MyModel.objects.filter(owners=user))

That's assuming that the __unicode__ method of your MyModel returns self.name. If this isn't the case, then you can subclass ModelChoiceField and override the label_from_instance method.

SmileyChris