1 from django.core.exceptions import ValidationError
2 from django.utils.translation import ugettext_lazy as _
3 from django.core.validators import URLValidator
7 class TreeParentValidator(object):
9 constructor takes instance and parent_attr, where instance is the model
10 being validated and parent_attr is where to look on that parent for the
13 #message = _("A tree element can't be its own parent.")
16 def __init__(self, instance, parent_attr=None, message=None, code=None):
17 self.instance = instance
18 self.parent_attr = parent_attr
19 self.static_message = message
23 def __call__(self, value):
25 Validates that the self.instance is not found in the parent tree of
26 the node given as value.
31 comparison=self.get_comparison(parent)
32 if comparison == self.instance:
33 # using (self.message, code=self.code) results in the admin interface
34 # screwing with the error message and making it be 'Enter a valid value'
35 raise ValidationError(self.message)
38 def get_comparison(self, parent):
39 if self.parent_attr and hasattr(parent, self.parent_attr):
40 return getattr(parent, self.parent_attr)
44 def get_message(self):
45 return self.static_message or _(u"A %s can't be its own parent." % self.instance.__class__.__name__)
46 message = property(get_message)
49 class TreePositionValidator(object):
52 def __init__(self, parent, slug, obj_class, message=None, code=None):
55 self.obj_class = obj_class
56 self.static_message = message
61 def __call__(self, value):
63 Validates that there is no obj of obj_class with the same position
64 as the compared obj (value) but a different id.
66 if not isinstance(value, self.obj_class):
67 raise ValidationError(_(u"The value must be an instance of %s." % self.obj_class.__name__))
70 obj = self.obj_class.objects.get(slug=self.slug, parent=self.parent)
72 if obj.id != value.id:
73 raise ValidationError(self.message)
75 except self.obj_class.DoesNotExist:
78 def get_message(self):
79 return self.static_message or _(u"A %s with that path (parent and slug) already exists." % self.obj_class.__name__)
80 message = property(get_message)
83 class URLRedirectValidator(URLValidator):
85 r'^(?:https?://' # http:// or https://
86 r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|' #domain...
87 r'localhost|' #localhost...
88 r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
89 r'(?::\d+)?' # optional port
90 r'|)' # also allow internal redirects
91 r'(?:/?|[/?]?\S+)$', re.IGNORECASE)
94 class URLLinkValidator(URLValidator):
96 r'^(?:https?://' # http:// or https://
97 r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|' #domain...
98 r'localhost|' #localhost...
99 r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
100 r'(?::\d+)?' # optional port
101 r'|)' # also allow internal links
102 r'(?:/?|[/?#]?\S+)$', re.IGNORECASE)