Sunday, 9 January 2011

Customising Django's uniqueness validation message

In case you've been wondering: you need to override the unique_error_message method on your model. The unique_check argument is a tuple containing field names that are supposed to be unique together (for regular uniqueness this is a one-element tuple). See the example below for validating the slug field:

class MyModel(models.Model):
slug = models.SlugField(max_length=200, unique=True)
  def unique_error_message(self, model_class, unique_check):
if unique_check == ("slug",):
return u"This slug is already taken"
return super(Office, self).unique_error_message(model_class, unique_check)

No comments: