Dec 15 2008

Removing Empty Labels from forms.ChoiceField in ModelFormSets

Category: Django,Pythonvbmendes @ 21:52

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)

Tags: , ,

10 Responses to “Removing Empty Labels from forms.ChoiceField in ModelFormSets”

  1. Carlo Pires says:

    Thanks. This helped me today!

  2. Victor H. says:

    Thx a lot!!

  3. automotive floor jack says:

    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?

  4. Vinicius Mendes says:

    Thanks for recognizing our efforts. The template is one of the defaults of wordpress with minor changes.

  5. mrben says:

    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)

    class Meta:
        model = MyModel
    

  6. Klaudia Saric says:

    Thanks for your post. I am new at django and this is a big help.

  7. Pozycjonowanie says:

    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.

  8. szkolenia bhp inowrocław says:

    It might not be written any better. Discovering this blog reminds me of some importantthings.

  9. imprezy opole says:

    Pleace let us be known , when you are going to publish some new articles. You are amazing writer.

  10. Jesenia Inestroza says:

    Excellent article over again. I am looking forward for more updates=)