Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@areski
Created August 8, 2014 13:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save areski/b9e293ad34d2b6845958 to your computer and use it in GitHub Desktop.
Save areski/b9e293ad34d2b6845958 to your computer and use it in GitHub Desktop.
Figuring out Django class-based validators
from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _, ungettext_lazy
from django.core.validators import MaxValueValidator, MinValueValidator
from django.utils.deconstruct import deconstructible
@deconstructible
class MaxWordValidator(object):
print "MaxWordValidator"
compare = lambda self, a, b: a > b
clean = lambda self, x: len(x)
message = ungettext_lazy(
'Ensure this value has at least %(limit_value)d word (it has %(show_value)d).',
'Ensure this value has at least %(limit_value)d words (it has %(show_value)d).',
'limit_value')
code = 'max_word_length'
def __init__(self, limit_value, message=None):
print "limit_value"
print limit_value
self.limit_value = limit_value
if message:
self.message = message
def __call__(self, value):
print value
cleaned = self.clean(value)
params = {'limit_value': self.limit_value, 'show_value': cleaned, 'value': value}
print params
if self.compare(cleaned, self.limit_value):
raise ValidationError(self.message, code=self.code, params=params)
def __eq__(self, other):
return (
isinstance(other, self.__class__)
and (self.limit_value == other.limit_value)
and (self.message == other.message)
and (self.code == other.code)
)
class MaxWordCharField(models.CharField):
default_validators = [MaxWordValidator(5)]
class TryModel(models.Model):
name = models.CharField(max_length=32)
intmax_field = models.IntegerField(default=10, validators=[MaxValueValidator(14)])
nextmax_field = models.IntegerField(default=21, validators=[MaxValueValidator(14)])
myfloat = models.FloatField(validators=[MinValueValidator(-100.00), MaxValueValidator(1000.00)])
maxword = MaxWordCharField(default="", max_length=150)
newmaxword = models.CharField(default="", max_length=150, validators=[MaxWordValidator(5)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment