3

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.

j08691
  • 204,283
  • 31
  • 260
  • 272
anonymous
  • 31
  • 3

1 Answers1

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.

You'll have to declare such arbitrary objects outside the Form subclass.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • Okay, I figured it was something like that. To be honest, I'm still relatively new with Python. Thanks a lot. – anonymous Jul 08 '17 at 23:55