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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With