1 from django.core.exceptions import ValidationError
2 from django.utils.translation import ugettext_lazy as _
5 class TreeParentValidator(object):
7 constructor takes instance and parent_attr, where instance is the model
8 being validated and parent_attr is where to look on that parent for the
11 #message = _("A tree element can't be its own parent.")
14 def __init__(self, instance, parent_attr=None, message=None, code=None):
15 self.instance = instance
16 self.parent_attr = parent_attr
17 self.static_message = message
21 def __call__(self, value):
23 Validates that the self.instance is not found in the parent tree of
24 the node given as value.
29 comparison=self.get_comparison(parent)
30 if comparison == self.instance:
31 # using (self.message, code=self.code) results in the admin interface
32 # screwing with the error message and making it be 'Enter a valid value'
33 raise ValidationError(self.message)
36 def get_comparison(self, parent):
37 if self.parent_attr and hasattr(parent, self.parent_attr):
38 return getattr(parent, self.parent_attr)
42 def get_message(self):
43 return self.static_message or _(u"A %s can't be its own parent." % self.instance.__class__.__name__)
44 message = property(get_message)
46 class TreePositionValidator(object):
49 def __init__(self, parent, slug, obj_class, message=None, code=None):
52 self.obj_class = obj_class
53 self.static_message = message
58 def __call__(self, value):
60 Validates that there is no obj of obj_class with the same position
61 as the compared obj (value) but a different id.
63 if not isinstance(value, self.obj_class):
64 raise ValidationError(_(u"The value must be an instance of %s." % self.obj_class.__name__))
67 obj = self.obj_class.objects.get(slug=self.slug, parent=self.parent)
69 if obj.id != value.id:
70 raise ValidationError(self.message)
72 except self.obj_class.DoesNotExist:
75 def get_message(self):
76 return self.static_message or _(u"A %s with that path (parent and slug) already exists." % self.obj_class.__name__)
77 message = property(get_message)