Django form: name 'self' not defined

I have a form in Django that looks like

class FooForm(forms.ModelForm): foo_field = forms.ModelChoiceField(widget=FooWidget(def_arg=self.data)) 

When I call self.data , Python throws a name 'self' is not defined exception. How can I access self ?

+7
source share
3 answers

As others have said, at this point there is no self . Something like this really works:

 class FooForm(forms.ModelForm): foo_field = forms.ModelChoiceField() def __init__(self, *args, **kwargs): super(FooForm, self).__init__(*args, **kwargs) self.fields['foo_field'].initial = self.data 

You can also access the widget in __init__ through self.fields['foo_field'].widget

+7
source

You can not

during class creation, there is no instance of the object. for such dynamic behavior you need to override the __init__ method and create a field (or change some of its parameters) there

+5
source

You can not; there is no self . You will need to do additional configuration in __init__() .

+2
source

All Articles