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