Customize Django Form ModelChoiceField

Django form ModelChoiceField or ModelMultipleChoiceField by default will render the field choices following the model __str__ or __unicode__.

Here is how to customize the representation of HTML choices for those fields.
In this case from my Customer model I need to render it in django form with the name and id_card.

class Customer(models.Model):
    name = models.CharField(max_length=120)
    id_card = models.CharField(max_length=20)

    def __unicode__(self):

class Group(models.Model):
    name = models.CharField(max_length=120)
    customers = models.ManyToManyField(Customer)

    def __unicode__(self):

Then create our custom field by subclass ModelMultipleChoiceField or ModelChoiceField.

class CustomOrderMultipleChoiceField(forms.ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return '{} - {}'.format(, obj.id_card)

The last you just need to apply to your form with your custom model field. 😀
And your html will no longer used model __str__ or __unicode__.

class CustomerForm(forms.ModelForm):
    customers = CustomOrderMultipleChoiceField(queryset=Customer.objects.all())

    class Meta:
        model = Group


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.