Search code examples
djangodjango-widgetdjango-forms

Django - CheckboxSelectMultiple without "------" choice


How can I remove "------" from rendered choices? I use in my model form:

widgets = {
    'event_form': forms.CheckboxSelectMultiple(),
}

In model I have IntegerField with choices:

EVENT_FORM_CHOICES = (
    (1, _(u'aaaa')),
    (2, _(u'bbbb')),
    (3, _(cccc')),
    (4, _(u'dddd')),
    (5, _(eeee'))
)

rendered choices contain --------- as first possible choice. How I can get rid of it?

EDIT: The only working way i figured out is (in init method):

tmp_choices = self.fields['event_form'].choices
del tmp_choices[0]
self.fields['event_form'].choices = tmp_choices

but it's not very elegant way :)


Solution

  • Django is including the blank choice because the field doesn't have a default value.

    If you set a default value in your model, then Django will not include the blank choice.

    class MyModel(models.Model):
        event_form = models.PositiveSmallIntegerField(choices=EVENT_FORM_CHOICES, default=1)
    

    If you don't want to set a default value in your model, then you can explicitly declare the field and choices in the model form, or change the choices in the model form's __init__ method.