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?
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
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
You can't; there is no self
there. You'll need to do additional setup in __init__()
.
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