正确的方法将`forms.ChoiceField`重写为ModelField?它是models.ForeignKey?

时间:2021-07-17 18:05:32

I am converting a survey from a Form to a ModelForm in Django 1.6.2 but I am having an issue selecting the right field type for ChoiceField. The survey was implemented using a SessionWizardView.

我正在将一个调查从Form转换为Django 1.6.2中的ModelForm,但是我在为ChoiceField选择正确的字段类型时遇到了问题。调查是使用SessionWizardView实现的。

My question is: What is the correct way of rewriting the below code which used to be in my forms.py into my models.py using ModelForm?

我的问题是:使用ModelForm将以下代码重写到我的models.py中的正确方法是什么?

The old code:

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)

The below is my attempt but from reading the documentation which lists corresponding Form fields for every Model field except ChoiceField, I am not 100% certain that I am correct.

以下是我的尝试,但是从阅读文档列出了除ChoiceField之外的每个Model字段的相应表单字段,我不是100%确定我是正确的。

The new code:

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?')

Is this correct?

它是否正确?

1 个解决方案

#1


No, it's not correct. Take a look at Django's choices documentation.

不,这不对。看看Django的选择文档。

Replace your line

替换你的线

sex = models.ForeignKey('Person', related_name='Person_sex',
                        null=True, choices=SEX, verbose_name='What sex are you?')

with

sex = models.CharField(max_length=1, choices=SEX,
                       verbose_name='What sex are you?', null=True)

The value stored in your database will be "F" or "M", but Django will display "Female" or "Male" in your ModelForm. There's a nice explanation about this here.

存储在数据库中的值将为“F”或“M”,但Django将在ModelForm中显示“Female”或“Male”。这里有一个很好的解释。

#1


No, it's not correct. Take a look at Django's choices documentation.

不,这不对。看看Django的选择文档。

Replace your line

替换你的线

sex = models.ForeignKey('Person', related_name='Person_sex',
                        null=True, choices=SEX, verbose_name='What sex are you?')

with

sex = models.CharField(max_length=1, choices=SEX,
                       verbose_name='What sex are you?', null=True)

The value stored in your database will be "F" or "M", but Django will display "Female" or "Male" in your ModelForm. There's a nice explanation about this here.

存储在数据库中的值将为“F”或“M”,但Django将在ModelForm中显示“Female”或“Male”。这里有一个很好的解释。