Customize/remove Django select box blank option

后端 未结 15 831
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 18:22

I\'m using Django 1.0.2. I\'ve written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a

15条回答
  •  再見小時候
    2020-11-30 19:15

    With Carl's answer as a guide and after rooting around the Django source for a couple hours I think this is the complete solution:

    1. To remove the empty option (extending Carl's example):

      class ThingForm(models.ModelForm):
        class Meta:
          model = Thing
      
        def __init__(self, *args, **kwargs):
          super(ThingForm, self).__init__(*args, **kwargs)
          self.fields['verb'].empty_label = None
          # following line needed to refresh widget copy of choice list
          self.fields['verb'].widget.choices =
            self.fields['verb'].choices
      
    2. To customize the empty option label is essentially the same:

      class ThingForm(models.ModelForm):
        class Meta:
          model = Thing
      
        def __init__(self, *args, **kwargs):
          super(ThingForm, self).__init__(*args, **kwargs)
          self.fields['verb'].empty_label = "Select a Verb"
          # following line needed to refresh widget copy of choice list
          self.fields['verb'].widget.choices =
            self.fields['verb'].choices
      

    I think this approach applies to all scenarios where ModelChoiceFields are rendered as HTML but I'm not positive. I found that when these fields are initialized, their choices are passed to the Select widget (see django.forms.fields.ChoiceField._set_choices). Setting the empty_label after initialization does not refresh the Select widget's list of choices. I'm not familiar enough with Django to know if this should be considered a bug.

提交回复
热议问题