我目前正在探索django表格并且有一个问题我希望有人可以帮助我。
我正在关注取自Creating forms from models | Django documentation
的示例我有表格;
# 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)
和模型;
#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
但是,当我尝试访问表单时收到以下错误;
/
处的NameError名称'TITLE_CHOICES'未定义
请求方法:GET请求URL: http://192.168.1.111:8000/ Django 版本:1.2.4例外类型: NameError异常值:name 'TITLE_CHOICES'未定义
我是否应该做些什么来允许forms.py访问models.py中的TITLE_CHOICES?
提前致谢。
答案 0 :(得分:3)
TITLE_CHOICES
:
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
以表格形式:
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)