【发布时间】:2015-05-12 14:52:24
【问题描述】:
我在 Django 1.6.2 中将调查从 Form 转换为 ModelForm,但在为 ChoiceField 选择正确的字段类型时遇到问题。该调查是使用 SessionWizardView 实施的。
我的问题是:使用 ModelForm 将我的 forms.py 中的以下代码重写为我的 models.py 的正确方法是什么?
旧代码:
forms.py
class SurveyFormA(forms.Form):
MALE = 'M'
FEMALE = 'F'
SEX = (
("", "----------"),
(MALE, "Male"),
(FEMALE, "Female"),
)
sex = forms.ChoiceField(widget=forms.Select(), choices=SEX, initial= "", label='What sex are you?', required = False)
以下是我的尝试,但通过阅读documentation,其中列出了除ChoiceField 之外的每个模型字段的相应表单字段,我不能 100% 确定我是正确的。
新代码:
forms.py
class SurveyFormA(forms.ModelForm):
class Meta:
model = Person
fields = ['sex']
models.py
class Person(models.Model):
MALE = 'M'
FEMALE = 'F'
SEX = (
(MALE, "Male"),
(FEMALE, "Female"))
sex = models.ForeignKey('Person', related_name='Person_sex', null=True, choices=SEX, verbose_name='What sex are you?')
这对吗?
【问题讨论】:
标签: django python-2.7 django-models django-forms