6

If a model's field is a choice or foreign key, the widget on the page is a select input or radios if you specify that. Django places "---------" in the first item as an unselected value. How can I override it or even remove it? I remember reading the way to do it but can't find it any more.

Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
Georgie Porgie
  • 2,100
  • 3
  • 24
  • 25

3 Answers3

8

From the Django forms doc:

By default the <select> widget used by ModelChoiceField will have a an empty choice at the top of the list. You can change the text of this label (which is "---------" by default) with the empty_label attribute, or you can disable the empty label entirely by setting empty_label=None:

field2 = forms.ModelChoiceField(queryset=..., empty_label=None)

If you need to do this on a ModelForm, I had an answer here.

Community
  • 1
  • 1
Dominique Guardiola
  • 3,431
  • 2
  • 22
  • 22
6

See : http://docs.djangoproject.com/en/dev/topics/forms/modelforms/

If the model field has choices set, then the form field's widget will be set to Select, with choices coming from the model field's choices. The choices will normally include the blank choice which is selected by default. If the field is required, this forces the user to make a selection. The blank choice will not be included if the model field has blank=False and an explicit default value (the default value will be initially selected instead).

Piotr Duda
  • 1,767
  • 11
  • 12
3

If it's a ModelForm, just set default=None in your model, like this:

choose = models.CharField(max_length=3, choices=choose_dict, default=None)
Marcio Cruz
  • 2,012
  • 1
  • 23
  • 30
  • -1: `default` is used at the database level, not at the form level. This just means that if the value is not set when creating the model object, the value will be set to `None`. Dangerous advice – Patrick May 10 '14 at 08:56
  • @Patrick not true (at least since Django 1.4). See http://stackoverflow.com/a/11721969/898423 – Eduard Luca Aug 13 '14 at 08:07
  • True, I've just checked the docs and it doesn't seem to be the case for the latest django https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.default – Patrick Aug 13 '14 at 09:57