36

I created a model with a foreign key in it:

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

and then I created a form with a ModelForm to display to the users:

class BookSubmitForm(ModelForm):
    class Meta:
        model = Book

and when I display the page with the form I get the Library choices but also the blank (--------) choice that comes by default.

I thought by having null=False and blank=False in the model that would get rid of that blank choice in the ModelForm but no. What can I do to only have actual choices in the list and not that one?

6 Answers 6

51

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

3
  • It sort of works but I still see the original ChoiceField in the form with the blank choice alongside the new one with the same label and same choices but without the blank choice. It looks this method is not overriding the form but expanding it with the same field.
    – Bastian
    Commented Jan 10, 2012 at 9:32
  • Ok my bad, it was a typo, I used an uppercase first letter like in your example "Library". When switching to a lowercase "library" it actually overrides the field. Thanks!
    – Bastian
    Commented Jan 10, 2012 at 10:01
  • 2
    Great! You can also simply self.fields['library'].empty_label = None if you're not going to change the queryset. Commented Dec 14, 2017 at 11:44
15

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:]
1
  • Only use this if you are not able to set a default value for the field in your model, which is a cleaner alternative (see Daniel Sokolowski's answer).
    – gengkev
    Commented Aug 2, 2018 at 7:37
13

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='')
    ...
1
  • 3
    Changing the model just to fit the form doesn't seem right. This should only be done if it makes sense for your model to behave this way. Commented Dec 14, 2017 at 11:42
12

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 
2
  • 3
    Somehow this doesnt work for me. I still see "---------" as one of the options if set empty_label = None as above. Is this still valid for Django 1.10?
    – Anupam
    Commented Jun 7, 2017 at 9:31
  • Actually, I figured it was a TypedChoiceField and hence @Mithril's answer below worked.
    – Anupam
    Commented Jun 7, 2017 at 10:23
0

Simply go to your list of choices (assuming you've made this a CharField) and provide the following code for None:

Also, remember that this is an example, not pertaining to the code in question. It is simply meant to help anyone struggling with a default option.

GENDER_CHOICES = (
    (None, 'Sex:'),
    ('M', 'Male'),
    ('F', 'Female'),
    ('G', 'Gay'),
    ('L', 'Lesbian'),
    ('B', 'Bi'),
    ('O', 'Other')
)
Choose_gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True)

By specifying None, you are telling the choice field to default to a certain string. If you want to default to nothing, simply put '' empty brackets.

1
  • With (None, ''),, an selectable box (albeit without ---------) is still shown.
    – SaeX
    Commented Dec 18, 2022 at 11:58
0

The accepted solution works for choice fields which handle relationships, but it won't work for model fields that have the choices field set.

For anyone stumbling upon this question while trying to hide the empty choice field when choices is set, I got it working by providing my own custom CSS to my model form.

I don't know that hiding the empty choice field makes a lot of sense when using the default Select widget, but it does for the RadioSelect widget.

Make sure to configure your static files setting and then run python manage.py collectstatic

/* STATICFILES_DIRS/css/my_customizations.css */
#id_field_name :has(input[value='']) {
  visibility: hidden;
  padding: 0;
  margin: 0;
  height: 0;
}
class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = "__all__"
        widgets = {"field_name": forms.RadioSelect()}
        # if you're using Django 3.x, you need set the class for inline
        # widgets = {"field_name": forms.RadioSelect(attrs={"class": "inline li"})}

    class Media:
        css = {"all": ("css/my_customizations.css",)}

This let me have the option be null initially in the database, but ensure that writers select one of the two fields, and not change it from a valid value to the unset one.

Though, as of January 2023, :has is not yet supported by Firefox, but will hopefully be supported sometime this year.

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Jan 15, 2023 at 20:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.