3

我的目标是能够使用 get_FOO_display(),据我所知,我必须在模型字段中指定选择。同时,我想使用 ModelForm 作为 RadioButton 来呈现表单。

我遇到的问题是,将在下拉选择中使用的默认值“------”显示为我的 RadioButton 选项之一。

模型.py

class Medication(models.Model):
    YESNO_CHOICES = [(0, 'No'), (1, 'Yes')]
    Allergies = models.BigIntegerField(verbose_name='Allergies:', choices=YESNO_CHOICES)

表格.py

我试过在 ModelForm 中指定一个 RadioButton 小部件。

class mfMedication(ModelForm):
    class Meta:
        model = Medication
        widgets = {
        'Allergies': RadioSelect(),
        }

并且还使用 CHOICES 指定 RadioButton。

class mfMedication(ModelForm):
    class Meta:
        model = Medication
        widgets = {
        'Allergies': RadioSelect(choices=Medication.YESNO_CHOICES),
        }

在这两种情况下,我都会得到三个单选按钮:

"": -------
0 : No
1 : Yes

我没有得到“-------”的唯一方法是从我的模型字段中删除选项=YESNO_CHOICES,但这会阻止 get_FOO_display() 工作。

您用来完成这项工作的任何方法都将不胜感激。

谢谢。京东。

4

2 回答 2

9

如果您想阻止显示-------选项,则应empty_label=None在表单字段中指定。

另外,我建议您将BooleanField用于模型,将 TypedChoiceField用于表单:

模型.py:

class Medication(models.Model):
    Allergies = models.BooleanField('Allergies:')

表格.py:

class MedicationForm(forms.ModelForm):
    YESNO_CHOICES = ((0, 'No'), (1, 'Yes'))
    Allergies = forms.TypedChoiceField(
                     choices=YESNO_CHOICES, widget=forms.RadioSelect, coerce=int
                )
于 2012-11-12T08:28:44.567 回答
1

使用 BigIntegerField,您还可以设置 default=0 或任何您想要的选择。

于 2016-08-04T15:20:04.550 回答