Reputation: 31
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
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.
Upvotes: 3
Views: 52
Reputation: 78546
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.
You'll have to declare such arbitrary objects outside the Form
subclass.
Upvotes: 1