Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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
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).',
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.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