Django View Class:name' self'没有定义

时间:2015-08-18 10:10:11

标签: python django django-forms

我正在研究Django框架。 现在,我正在为下面的用户注册创建一个类。 我在第6行遇到错误。 你能帮忙吗?

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

1 个答案:

答案 0 :(得分:3)

这与Django无关;类定义的主体有自己的命名空间,并按写入的顺序运行,所以此时:

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

不仅self未定义, makeYearChoice也不是!您可以通过以下两种方式解决此问题之一:

  1. 移动方法定义上面类属性的设置,并直接调用

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

    一旦定义了类,就会给你一个冗余的实例方法;或

  2. 将它作为一个独立的函数,只需在类中调用它:

    def makeYearChoice(startYear):
        ...
    
    class JoinForm(forms.Form):
        ...
        YEAR = makeYearChoice(1940)  # no fuss about self argument
        ...
    
  3. 我强烈赞成后者。另外,你应该阅读the style guide;方法和属性名称通常为lowercase_with_underscores,逗号后应该有空格。