isUnique validator for newforms

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
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 }

More like this

  1. use oldforms validators in newforms forms by garywilson 4 years, 10 months ago
  2. Add validation for 'unique' and 'unique_together' constraints to newforms created dynamically via form_for_model or form_for_instance by mp 4 years, 8 months ago
  3. Custom admin widgets by field type by dgouldin 2 years, 11 months ago
  4. unique validation for ModelForm by whiskybar 3 years, 10 months ago
  5. Validation for 'unique' and 'unique_together' constraints (different version) by miracle2k 4 years, 6 months ago

Comments

(Forgotten your password?)