Empty Label ChoiceField Django

后端 未结 7 931
猫巷女王i
猫巷女王i 2020-12-23 19:38

How do you make ChoiceField\'s label behave like ModelChoiceField? Is there a way to set an empty_label, or at least show a blank fiel

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-23 20:16

    A little late to the party..

    How about not modifying the choices at all and just handling it with a widget?

    from django.db.models import BLANK_CHOICE_DASH
    
    class EmptySelect(Select):
        empty_value = BLANK_CHOICE_DASH[0]
        empty_label = BLANK_CHOICE_DASH[1]
    
        @property
        def choices(self):
            yield (self.empty_value, self.empty_label,)
            for choice in self._choices:
                yield choice
    
        @choices.setter
        def choices(self, val):
            self._choices = val
    

    Then just call it:

    class SomeForm(forms.Form):
        # thing = forms.ModelChoiceField(queryset=Thing.objects.all(), empty_label='Label')
        color = forms.ChoiceField(choices=COLORS, widget=EmptySelect)
        year = forms.ChoiceField(choices=YEAR_CHOICES, widget=EmptySelect)
    

    Naturally, the EmptySelect would be placed inside some kind of common/widgets.py code and then when ever you need it, just reference it.

提交回复
热议问题