Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass parameter to Form in Django

I have a custom form to which I would like to pass a parameter. Following this example I came up with the following code :

class EpisodeCreateForm(forms.Form):
    def __init__(self, *args, **kwargs):
        my_arg = kwargs.pop('my_arg')
        super(EpisodeCreateForm, self).__init__(*args, **kwargs)

    my_field = forms.CharField(initial=my_arg)

But I get the following error:

Exception Value: name 'my_arg' is not defined

How can I get it to recognize the argument in the code of the form ?

like image 414
Johanna Avatar asked Aug 31 '11 14:08

Johanna


1 Answers

You need to set the initial value by referring to the form field instance in __init__. To get access to the form field instance in __init__, put this before the call to super:

self.fields['my_field'].initial=my_arg

And remove initial=my_arg from where you declare my_field because at that point (when class is declared) my_arg is not in scope.

like image 51
sandinmyjoints Avatar answered Oct 09 '22 22:10

sandinmyjoints