问题
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.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:
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:
class JoinForm(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:
Move the method definition above the setting of the class attribute, 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 once the class is defined; or
Make it a standalone function and just call it within the class:
def makeYearChoice(startYear): ... class JoinForm(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.
来源:https://stackoverflow.com/questions/32069479/django-view-class-name-self-is-not-defined