Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django form: name 'self' is not defined

Tags:

django

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?

like image 316
sans Avatar asked Jan 06 '12 23:01

sans


3 Answers

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

like image 154
dgel Avatar answered Oct 05 '22 21:10

dgel


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

like image 27
second Avatar answered Oct 05 '22 22:10

second


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

like image 36
Ignacio Vazquez-Abrams Avatar answered Oct 05 '22 21:10

Ignacio Vazquez-Abrams