When you use a Model Choice Field in Django, it automatically creates an empty option in the generated select widget. But in some special cases, you don’t want this empty option to be there. So I decided to find the way to remove it. It’s much more simple then you think. Just create your model declaring the model choice field like this:
fieldname = forms.ModelChoiceField(queryset=RelationModel.objects,empty_label=None)
It’s simple like that. Just set the empty_label argument to None. But whe using ModelFormSets, there is a little more work to do. You have to create a new BaseModelFormSet like this:
from django.forms.models import BaseModelFormSet</p>
<p>class MyBaseModelFormSet(BaseModelFormSet):
def add_fields(self, form, index):
super(MyBaseModelFormSet,self).add_fields(form,index)
form.fields['fieldname'] = forms.ModelChoiceField(queryset=RelationModel.objects,empty_label=None)
Pay atention that you have to override the add_fields method and change your field in the form fields array. Finally you have to pass this BaseModelFormSet as argument to the modelformset_factory:
from django.forms.models import modelformset_factory</p> <p>MyModelFormset = modelformset_factory(MyModel,formset=MyBaseModelFormSet)

February 25th, 2009 15:15
Thanks. This helped me today!
March 7th, 2009 19:54
Thx a lot!!
March 14th, 2009 09:49
It’s the first time I commented here and I should say that you provide genuine, and quality information for other bloggers! Good job. p.s. You have a very good template for your blog. Where have you got it from?
March 14th, 2009 19:12
Thanks for recognizing our efforts. The template is one of the defaults of wordpress with minor changes.
February 3rd, 2010 11:27
FWIW your title is misleading – ModelChoiceField has an empty_label attribute, but ChoiceField doesn’t. However, you can overwrite in the same way by simply passing a list of choices into the field at the form level:
class MyModelForm(forms.ModelForm): myfield = forms.ChoiceField(choices = MY_CHOICES)
March 6th, 2010 16:35
Thanks for your post. I am new at django and this is a big help.
December 4th, 2010 07:42
This are some of the bestdirections I’ve ever? read. This is the impressive article for not olny anyone who is new on this topic.
December 17th, 2010 08:45
It might not be written any better. Discovering this blog reminds me of some importantthings.
December 17th, 2010 10:00
Pleace let us be known , when you are going to publish some new articles. You are amazing writer.
January 25th, 2011 19:34
Excellent article over again. I am looking forward for more updates=)