How to remove the No 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 would like to have is to select a radio with two parameters ("type 1" and "type 2"). However, I will have 3 options: "---------", "type 1" and "type 2". "---------" for "No", I think, but the "type" field is required in the model, why is the "No" parameter still displayed?

But if I use a 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 would like to use ModelForm over the standard form, but donโ€™t know how to remove "---------". Can anyone help me out? Thanks.

UPDATE: Thank you guys just found the answer to here .

Looks like I have to override the method or ModelForm.

+4
source share
4 answers

You can set empty_label to None for this.

 type = forms.ChoiceField(widget=forms.RadioSelect(), choices=Item.TYPE_CHOICES, empty_label=None) 
+5
source

There is a much simpler way, without overriding anything: just add default=1 like this:

 type = models.PositiveSmallIntegerField(max_length=1, choices=TYPE_CHOICES, default=1) 

Found this in a Django source:

  include_blank = (self.blank or not (self.has_default() or 'initial' in kwargs)) 
0
source

If you have a modelForm, you must rewrite the field in the form using forms.ModelChoiceField() instead of models.ChoiceField() , and then add parameters as shown above to replace the options with the query.

 type = forms.ModelChoiceField(widget=forms.RadioSelect(), empty_label=None, queryset=TYPE.objects.all()) 
0
source

As I see it, this is a duplicate of how-to-get-rid-of-the-bogus-choice-generated-by-radioselect-of-django-form

There is an answer, and additional links hopefully help.

EDIT

so maybe if you try this, (I didnโ€™t do this, no guarantees :))

 widget = { 'type': forms.RadioSelect(choices=Item.TYPE_CHOICES), } 
-1
source

All Articles