from django.db.models import Model from django.forms import ValidationError from django.utils.translation import ugettext as _ from django.utils.text import capfirst def isUnique( instance, field, data ): "Validates that a value is unique for a field." if not isinstance( instance, Model ): raise TypeError, u'The instance passed to isUnique is not a subclass of django.db.models.Model' model = instance.__class__ try: matching_obj = model.objects.get( **{ field: data } ) except model.DoesNotExist: return data if instance and instance.pk == matching_obj.pk: return data raise ValidationError, _( u'%(optname)s with this %(fieldname)s already exists.' ) % {'optname': capfirst( model._meta.verbose_name ), 'fieldname': model._meta.get_field( field, many_to_many = False ).verbose_name }