I've defined the following form class in a Django project (Django 1.11, Python 3.5), but when I execute python3 manage.py runserver
, I receive a
我在Django项目(Django 1.11, Python 3.5)中定义了以下表单类,但是在执行python3 manage时。py runserver,我收到a
NameError: name 'month_names' is not defined
class MonthForm(forms.Form):
month_names = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
]
MONTH_CHOICES = [(i + 1, month_names[i]) for i in range(len(month_names))]
month = forms.ChoiceField(choices=MONTH_CHOICES, label='Month',
widget=forms.Select())
I can't figure out why this doesn't work. I've noticed that if I move the initial month_names
assignment outside of the class definition, then it works. Any explanation would be greatly appreciated. Thank you in advance.
我搞不懂为什么这行不通。我注意到,如果我将最初的月度名称赋值移动到类定义之外,那么它就可以工作。如有任何解释,将不胜感激。提前谢谢你。
1 个解决方案
#1
1
The Form
metaclass - DeclarativeFieldsMetaclass
- does not allow you to create (and by extension, bind) arbitrary objects that are not fields (i.e. instance of django.forms.fields.Field
) on the class.
表单元类——DeclarativeFieldsMetaclass——不允许您在类上创建(并通过扩展绑定)非字段的任意对象(例如django.forms.fields.Field的实例)。
You'll have to declare such arbitrary objects outside the Form
subclass.
您必须在表单子类之外声明这些任意对象。
#1
1
The Form
metaclass - DeclarativeFieldsMetaclass
- does not allow you to create (and by extension, bind) arbitrary objects that are not fields (i.e. instance of django.forms.fields.Field
) on the class.
表单元类——DeclarativeFieldsMetaclass——不允许您在类上创建(并通过扩展绑定)非字段的任意对象(例如django.forms.fields.Field的实例)。
You'll have to declare such arbitrary objects outside the Form
subclass.
您必须在表单子类之外声明这些任意对象。