将 `forms.ChoiceField` 重写为 ModelField 的正确方法?是models.ForeignKey吗?
Correct way of rewriting `forms.ChoiceField` into a ModelField? Is it models.ForeignKey?
我在 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's choices
documentation.
替换你的线路
sex = models.ForeignKey('Person', related_name='Person_sex',
null=True, choices=SEX, verbose_name='What sex are you?')
和
sex = models.CharField(max_length=1, choices=SEX,
verbose_name='What sex are you?', null=True)
存储在您的数据库中的值将是 "F" 或 "M",但 Django 将在您的 ModelForm
中显示 "Female" 或 "Male"。关于这个 here.
有一个很好的解释
我在 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's choices
documentation.
替换你的线路
sex = models.ForeignKey('Person', related_name='Person_sex',
null=True, choices=SEX, verbose_name='What sex are you?')
和
sex = models.CharField(max_length=1, choices=SEX,
verbose_name='What sex are you?', null=True)
存储在您的数据库中的值将是 "F" 或 "M",但 Django 将在您的 ModelForm
中显示 "Female" 或 "Male"。关于这个 here.