Empty Label ChoiceField Django

后端 未结 7 956
猫巷女王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:14

    I know you already accepted an answer but I just want to post this in case someone out there runs into the issue I was having, namely the accepted solution does not work with a ValueListQuerySet. The EmptyChoiceField, which you linked to, works perfectly for me (although I am using django 1.7).

    class EmptyChoiceField(forms.ChoiceField):
        def __init__(self, choices=(), empty_label=None, required=True, widget=None, label=None, initial=None, help_text=None, *args, **kwargs):
    
            # prepend an empty label if it exists (and field is not required!)
            if not required and empty_label is not None:
                choices = tuple([(u'', empty_label)] + list(choices))
    
            super(EmptyChoiceField, self).__init__(choices=choices, required=required, widget=widget, label=label, initial=initial, help_text=help_text, *args, **kwargs) 
    
    class FilterForm(forms.ModelForm):
        #place your other fields here 
        state = EmptyChoiceField(choices=People.objects.all().values_list("state", "state").distinct(), required=False, empty_label="Show All")
    

提交回复
热议问题