Overriding fForm class __init__ method

21 views
Skip to first unread message

DevelopsDjangoApps

unread,
Jun 16, 2010, 5:30:58 AM6/16/10
to Django users
Hi,

I have created a form class like this:

class VoteRadioForm(forms.Form):

choices =
forms.ModelChoiceField(queryset=Choice.objects.filter(poll__active=
True, poll__id = 2),
empty_label= None,
widget= forms.RadioSelect,
)

This class gives me dynamic number of entries for my form, based on
the poll_id. But as you may have already seen it, the poll__id is
hardcoded in this example. In order to pass different values to
poll__id, I tried to generated my choices element inside the __init__
method like this:

#choices =
forms.ModelChoiceField(queryset=Choice.objects.filter(poll__active=
True, poll__id = 2),
def __init__(self, pid = None, *args, **kwargs):
super(VoteRadioForm, self).__init__()
self.fields['ch'] =
forms.ModelChoiceField(queryset=Choice.objects.filter(poll__active=
True, poll__id = pid),
empty_label= None,
widget= forms.RadioSelect,
)

The first example(Hardcoded version) works perfectly fine. The second
example generates the form correctly, when I use:

form = VoteRadioForm(i)

However, when I try to validate the data and pass the request object
to it, it gives me the following error:

int() argument must be a string or a number, not 'QueryDict'

I even tried to add *args and **kwargs arguments when initializing my
class, just like this example:

http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/

But, it doesn't make any difference.

I'm having Pythong 2.6.5 on my Arch Linux machine.

I was wondering if anyone has ever had such problem?

Thanks in advance

Daniel Roseman

unread,
Jun 16, 2010, 6:51:02 AM6/16/10
to Django users
It's because your 'pid' parameter is grabbing the first argument to
the function, which is usually the posted data.

Instead, do this:

def __init__(self, *args, **kwargs):
pid = kwargs.pop('pid', None)
super(VoteRadioForm, self).__init__(*args, **kwargs)
...etc...

--
DR.

DevelopsDjangoApps

unread,
Jun 16, 2010, 7:23:51 AM6/16/10
to Django users
Thanks a lot. Your solution was the right one. However, I just needed
to provide 'pid' as the only argument for the pop method.

Now when I use the following command in my view it doesn't give me any
error:

form = VoteRadioForm(request.POST, pid = 2 )

However, I'm having a problem with form validation since is_valid
returns false. I think my form is not created correctly. Because when
I issue cleaned_data method, I get the following error:

'VoteRadioForm' object has no attribute 'cleaned_data'

I need to sleep now. Hopefully, tomorrow I am able to figure out this
problem.

Thanks
Reply all
Reply to author
Forward
0 new messages