指定模型中的选项和ModelForm中的RadioButton渲染未选中的值"------"

jon*_*man 3 django django-models django-forms

我的目标是能够使用get_FOO_display(),因此据我所知,我必须在模型字段中指定选项.同时我想使用ModelForm作为RadioButton渲染表单.

The problem I am having is that the default value of "------" that would be used in a dropdown select is showing up as one of my RadioButton options.

models.py

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

forms.py

I have tried just specifying a RadioButton widget in the ModelForm.

class mfMedication(ModelForm):
    class Meta:
        model = Medication
        widgets = {
        'Allergies': RadioSelect(),
        }
Run Code Online (Sandbox Code Playgroud)

and also specifying the RadioButton with the CHOICES.

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

In both cases I get three radiobuttons:

"": -------
0 : No
1 : Yes
Run Code Online (Sandbox Code Playgroud)

The only way I do not get the "-------" is to remove choices=YESNO_CHOICES from my model field, but this stops get_FOO_display() from working.

Any approach that you have used to get this working would be greatly appreciated.

Thanks. JD.

Ser*_*ney 8

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

另外,我建议你使用BooleanField作为模型,使用TypedChoiceField作为表单:

models.py:

class Medication(models.Model):
    Allergies = models.BooleanField('Allergies:')
Run Code Online (Sandbox Code Playgroud)

forms.py:

class MedicationForm(forms.ModelForm):
    YESNO_CHOICES = ((0, 'No'), (1, 'Yes'))
    Allergies = forms.TypedChoiceField(
                     choices=YESNO_CHOICES, widget=forms.RadioSelect, coerce=int
                )
Run Code Online (Sandbox Code Playgroud)