Login

isUnique validator for newforms

Author:
clamothe
Posted:
July 28, 2008
Language:
Python
Version:
.96
Tags:
newforms admin unique
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. Add validation for 'unique' and 'unique_together' constraints to newforms created dynamically via form_for_model or form_for_instance by bikeshedder 7 years, 10 months ago
  2. Validation for 'unique' and 'unique_together' constraints (different version) by miracle2k 7 years, 8 months ago
  3. Unique FileFiled or FileFiled with custom validation and overwriting files on update by evilclay 4 years, 3 months ago
  4. Unique field inline formset by dcwatson 2 years, 7 months ago
  5. Custom admin widgets by field type by dgouldin 6 years, 1 month ago

Comments

Please login first before commenting.