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

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 

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


If you specify blank=False and default=<VALUE> on the model field definition then Django will not render the blank choice by default; do note that the default value can be an invalid choice and set to '' or any invalid choice for example.

class Book(models.Model):
    library = models.ForeignKey(Library, null=False, blank=False, default='')
    ...

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:]

Tags:

Forms

Django