Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove "None" option in Django ModelForm?

For example, I have a model like this:

class Item(models.Model):
    TYPE_CHOICES = (
        (1, _('type 1')),
        (2, _('type 2')),
    )
    type = models.PositiveSmallIntegerField(max_length=1, choices=TYPE_CHOICES)

And for the form I have:

class ItemModelForm(forms.ModelForm):
    class Meta:
        model = Item
        widget = {
            'type': forms.RadioSelect(),
        }

What I'd like to have is a radio select with 2 options ("type 1" and "type 2"). However, I will have 3 options, "---------", "type 1" and "type 2". The "---------" is for "None" I think, but the "type" field is required in the model, why does the "None" option still show up?

But if I use Form instead:

class ItemForm(forms.Form):
    type = forms.ChoiceField(widget=forms.RadioSelect(), choices=Item.TYPE_CHOICES)

I will have only 2 options, "type 1" and "type 2", which is correct.

I'd like to use ModelForm over standard Form, but don't know how to remove the "---------". Could anybody help me? Thanks.

UPDATE: Thanks guys, just found that it has been answered here.

Looks like I will have to override either the field or method of the ModelForm.

like image 252
devfeng Avatar asked Sep 14 '11 17:09

devfeng


1 Answers

You should be able to set empty_label to None for this.

type = forms.ChoiceField(widget=forms.RadioSelect(), choices=Item.TYPE_CHOICES, empty_label=None)
like image 56
Uku Loskit Avatar answered Oct 05 '22 22:10

Uku Loskit