开发者

NameError when trying to populate form field from model

I'm currently exploring django forms and have a issue I hope someone can help me with.

I'm following an example taken from Creating forms from models | Django documentation

I have the form;

# forms.py

from django import forms
from my_project.my_app.models import Author

class AuthorForm(forms.Form):
    name = forms.CharField(max_length=100)
    title = forms.CharField(max_length=3,
            widget=forms.Select(choices=TITLE_CHOICES))
    birth_date = forms.DateField(required=False)

and the model;

#models.py

from django.db import models

TITLE_CHOICES = (
    ('MR', 'Mr.'),
    ('MRS', 'Mrs.'),
    ('MS', 'Ms.'),
)
class Author(models.Model):
    name = models.CharField(max_length=100)
    title = models.CharField(max_length=3, choices=TITLE_CHOICES)
    birth_date = models.DateField(blank=True, null=True)

    def __unicode__(self):
        return self.name

However, when I receive the following error when I try to access the form;

NameError at /

name 'TITLE_CHOICES' is not defined

Request Method: GET Request UR开发者_如何学PythonL: http://192.168.1.111:8000/ Django Version: 1.2.4 Exception Type: NameError Exception Value: name 'TITLE_CHOICES' is not defined

Is there something I should be doing to allow forms.py to access TITLE_CHOICES in models.py?

Thanks in advance.


TITLE_CHOICES should be defined inside of the class:

from django.db import models

class Author(models.Model):
    TITLE_CHOICES = (
        ('MR', 'Mr.'),
        ('MRS', 'Mrs.'),
        ('MS', 'Ms.'),
    )
    name = models.CharField(max_length=100)
    title = models.CharField(max_length=3, choices=TITLE_CHOICES)
    birth_date = models.DateField(blank=True, null=True)

    def __unicode__(self):
        return self.name

And in the form:

from django import forms
from my_project.my_app.models import Author

class AuthorForm(forms.Form):
    name = forms.CharField(max_length=100)
    title = forms.CharField(max_length=3,
            widget=forms.Select(choices=Author.TITLE_CHOICES))
    birth_date = forms.DateField(required=False)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜