sans
sans

Reputation: 2199

Django form: name 'self' is not defined

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

Answers (3)

dgel
dgel

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

second
second

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

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799062

You can't; there is no self there. You'll need to do additional setup in __init__().

Upvotes: 2

Related Questions