Customize Django’s unique_together Error Message

While you’re able to customize the error message for a unique field when defining your model…

class Context(models.Model):
name = models.CharField(error_messages={'unique': u'My custom message'})

view raw

hosted with ❤ by GitHub

…you can’t do the same for a unique_together constraint. There’s an open ticket but it hasn’t seen much attention. In the meantime, you can override the unique_error_message in your model to provide a custom error message:

def unique_error_message(self, model_class, unique_check):
if model_class == type(self) and unique_check == ('field1', 'field2'):
return 'Your custom error message.'
return super(YourModel, self).unique_error_message(model_class, unique_check)

view raw

hosted with ❤ by GitHub

2 thoughts on “Customize Django’s unique_together Error Message”

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 )

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