Django View class: name 'self' is undefined

I am working on a Django map. Now I am creating a class for user registration as shown below. I got an error on line number 6. Could you help?

1: class JoinForm(forms.Form):
2:    MONTH = {
3:        1:('Jan'), 2:('Feb'), 3:('March'), 4:('Apl'), 5:('May'), 6:('Jun'),
4:        7:('July'), 8:('Aug'), 9:('Sep'), 10:('Oct'), 11:('Nov'), 12:('Dec')
5:    }
6:    YEAR = self.makeYearChoice(self,1940)
7:    email = forms.EmailField(label='Email Address', max_length=50)
8:    name = forms.CharField(label='Real Name', max_length=20)
9:    birth = forms.DateField(label='Birth Date', widget=SelectDateWidget(years=YEAR, months=MONTH))
10:   loc = forms.CharField(label='Resident Location', max_length=40)
11:   passwd = forms.CharField(label='Password', max_length=16, widget=forms.PasswordInput)

12:   def makeYearChoice(self,startYear):
13:       YEARS = ();
14:       thisYear = datetime.now().year
15:       for year in range(startYear,thisYear):
16:           YEARS.append(year)
17:       return YEARS

      

0


source to share


1 answer


This is not related to Django; the body of your class definition has its own namespace and works in the order shown in this clause:

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

      

not only is self

not defined, it is makeYearChoice

also not! You can fix this in one of two ways:



  • Move the method definition above the class attribute setting and call it directly

    class JoinForm(forms.Form):
        ...
        def makeYearChoice(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 after the class is defined; or

  • Make it a standalone function and just call it inside the class:

    def makeYearChoice(startYear):
        ...
    
    class JoinForm(forms.Form):
        ...
        YEAR = makeYearChoice(1940)  # no fuss about self argument
        ...
    
          

I would strongly support the latter. Also, you should read the style guide ; method and attribute names are common lowercase_with_underscores

and you must have spaces after the commas.

+3


source







All Articles