gpt4 book ai didi

python - Django View 类: name 'self' is not defined

转载 作者:行者123 更新时间:2023-11-30 23:07:43 24 4
gpt4 key购买 nike

我正在研究 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

最佳答案

这与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
    ...

我强烈支持后者。另外,您应该阅读the style guide ;方法和属性名称通常为 lowercase_with_underscores,并且逗号后应有空格。

关于python - Django View 类: name 'self' is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32069479/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com