【问题标题】:Correct way of rewriting `forms.ChoiceField` into a ModelField? Is it models.ForeignKey?将“forms.ChoiceField”重写为 ModelField 的正确方法?是models.ForeignKey吗?
【发布时间】: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


    【解决方案1】:

    不,这是不正确的。看看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 中显示“女性”或“男性”。关于这个here有一个很好的解释。

    【讨论】:

      猜你喜欢
      • 2012-10-02
      • 1970-01-01
      • 1970-01-01
      • 2014-12-17
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      • 1970-01-01
      • 2012-05-03
      相关资源
      最近更新 更多