+class TargetURLModel(models.Model):
+ target_node = models.ForeignKey(Node, blank=True, null=True, related_name="%(app_label)s_%(class)s_related")
+ url_or_subpath = models.CharField(max_length=200, validators=[RedirectValidator()], blank=True, help_text="Point to this url or, if a node is defined and accepts subpaths, this subpath of the node.")
+ reversing_parameters = JSONField(blank=True, help_text="If reversing parameters are defined, url_or_subpath will instead be interpreted as the view name to be reversed.")
+
+ def clean(self):
+ # Should this be enforced? Not enforcing it would allow creation of "headers" in the navbar.
+ if not self.target_node and not self.url_or_subpath:
+ raise ValidationError("Either a target node or a url must be defined.")
+
+ if self.reversing_parameters and not (self.url_or_subpath or self.target_node):
+ raise ValidationError("Reversing parameters require either a view name or a target node.")
+
+ try:
+ self.get_target_url()
+ except (NoReverseMatch, ViewCanNotProvideSubpath), e:
+ raise ValidationError(e.message)
+
+ super(TargetURLModel, self).clean()
+
+ def get_reverse_params(self):
+ params = self.reversing_parameters
+ args = isinstance(params, list) and params or None
+ kwargs = isinstance(params, dict) and params or None
+ return self.url_or_subpath, args, kwargs
+
+ def get_target_url(self):
+ node = self.target_node
+ if node is not None and node.accepts_subpath and self.url_or_subpath:
+ if self.reversing_parameters is not None:
+ view_name, args, kwargs = self.get_reverse_params()
+ subpath = node.view.reverse(view_name, args=args, kwargs=kwargs)
+ else:
+ subpath = self.url_or_subpath
+ if subpath[0] != '/':
+ subpath = '/' + subpath
+ return node.construct_url(subpath)
+ elif node is not None:
+ return node.get_absolute_url()
+ else:
+ if self.reversing_parameters is not None:
+ view_name, args, kwargs = self.get_reverse_params()
+ return reverse(view_name, args=args, kwargs=kwargs)
+ return self.url_or_subpath
+ target_url = property(get_target_url)
+
+ class Meta:
+ abstract = True
+
+
+class Redirect(View, TargetURLModel):