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.

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

    def __unicode__(self):
         return self.name

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

    def __unicode__(self):
        return self.name

Then create our custom field by subclass ModelMultipleChoiceField or ModelChoiceField.

# fields.py
class CustomOrderMultipleChoiceField(forms.ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return '{} - {}'.format(obj.name, 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__.

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

    class Meta:
        model = Group

Reference: https://docs.djangoproject.com/en/1.8/ref/forms/fields/#modelchoicefield

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s