Skip to content Skip to sidebar Skip to footer

Django View Class : Name 'self' Is Not Defined

I'm working on the Django framework. Now I'm making a Class for user registration like below. I got a error on the line number 6. Could you give some help? 1: class JoinForm(forms.

Solution 1:

This is unrelated to Django; the body of your class definition has its own namespace, and runs in the order written, so at this point:

classJoinForm(forms.Form):
    ...
    YEAR = self.makeYearChoice(self,1940)  # here
    ...

not only is self not defined, makeYearChoice isn't either! You could fix this one of two ways, either:

  1. Move the method definition above the setting of the class attribute, and call it directly

    classJoinForm(forms.Form):
        ...
        defmakeYearChoice(self, startYear):  # define the method first
            ...
    
        YEAR = makeYearChoice(None,1940)  # don't have an instance, but who cares?
        ...
    

    which leaves you with a redundant instance method once the class is defined; or

  2. Make it a standalone function and just call it within the class:

    defmakeYearChoice(startYear):
        ...
    
    classJoinForm(forms.Form):
        ...
        YEAR = makeYearChoice(1940)  # no fuss about self argument
        ...
    

I would strongly favour the latter. Also, you should read the style guide; method and attribute names are generally lowercase_with_underscores, and you should have spaces after commas.

Post a Comment for "Django View Class : Name 'self' Is Not Defined"