Reputation: 2199
I have a form in Django that looks like this
class FooForm(forms.ModelForm):
foo_field = forms.ModelChoiceField(widget=FooWidget(def_arg=self.data))
Where I call self.data
, Python throws the exception name 'self' is not defined
. How can I access self
there?
Upvotes: 9
Views: 9912
Reputation: 16806
As others have answered, there is no self
to refer to at that point. Something like this does work though:
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
Upvotes: 14
Reputation: 28637
you can't
at the time the class is created, there is no object instance. for this kind of dynamic behaviour, you need to override the __init__
method and create the field (or change some of its parameters) there
Upvotes: 5
Reputation: 799062
You can't; there is no self
there. You'll need to do additional setup in __init__()
.
Upvotes: 2