Django, how to remove the blank choice from the choicefield in modelform? Django, how to remove the blank choice from the choicefield in modelform? django django

Django, how to remove the blank choice from the choicefield in modelform?


See ModelChoiceField. You have to set empty_label to None. So your code will be something like:

class BookSubmitForm(ModelForm):    library = ModelChoiceField(queryset=Library.objects, empty_label=None)    class Meta:        model = Book    

EDIT:changed the field name to lower case


self.fields['xxx'].empty_label = None would not work If you field type is TypedChoiceField which do not have empty_label property.What should we do is to remove first choice:

class BookSubmitForm(forms.ModelForm):    def __init__(self, *args, **kwargs):        super(BookSubmitForm, self).__init__(*args, **kwargs)        for field_name in self.fields:            field = self.fields.get(field_name)            if field and isinstance(field , forms.TypedChoiceField):                field.choices = field.choices[1:]


If you use ModelForm then you don't have to specify queryset, required, label, etc. But for the upvoted answer you have to do it again.

Actually you can do this to avoid re-specifying everything

class BookSubmitForm(ModelForm):    def __init__(self, *args, **kwargs):        super(BookSubmitForm, self).__init__(*args, **kwargs)        self.fields['library'].empty_label = None    class Meta:        model = Book