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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With