Login

isUnique validator for newforms

Author:
clamothe
Posted:
July 28, 2008
Language:
Python
Version:
.96
Score:
0 (after 0 ratings)

This is a generic unique field value validator for use with newforms. ( It's handy to plug into newforms-admin.)

Example, with newforms-admin:

` class LinkAdminForm( ModelForm ): def clean_url( self ): return isUnique( self.instance, 'url', self.cleaned_data['url'])

class LinkAdmin( ModelAdmin ): form = LinkAdminForm

site.register( Link, LinkAdmin ) `

 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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.