1 |
1 |
# Decorating URL includes, <https://djangosnippets.org/snippets/2532/>
|
2 |
2 |
|
3 |
|
from django.urls import RegexURLPattern, RegexURLResolver
|
|
3 |
try:
|
|
4 |
from django.urls import URLPattern, URLResolver
|
|
5 |
except ImportError:
|
|
6 |
# django < 2.0 compatibility
|
|
7 |
from django.urls import RegexURLPattern as URLPattern, RegexURLResolver as URLResolver
|
4 |
8 |
|
5 |
|
class DecoratedURLPattern(RegexURLPattern):
|
|
9 |
|
|
10 |
class DecoratedURLPattern(URLPattern):
|
6 |
11 |
def resolve(self, *args, **kwargs):
|
7 |
12 |
result = super(DecoratedURLPattern, self).resolve(*args, **kwargs)
|
8 |
13 |
if result:
|
9 |
14 |
result.func = self._decorate_with(result.func)
|
10 |
15 |
return result
|
11 |
16 |
|
12 |
|
class DecoratedRegexURLResolver(RegexURLResolver):
|
|
17 |
class DecoratedRegexURLResolver(URLResolver):
|
13 |
18 |
def resolve(self, *args, **kwargs):
|
14 |
19 |
result = super(DecoratedRegexURLResolver, self).resolve(*args, **kwargs)
|
15 |
20 |
if result:
|
... | ... | |
20 |
25 |
urlconf_module, app_name, namespace = includes
|
21 |
26 |
|
22 |
27 |
for item in urlconf_module:
|
23 |
|
if isinstance(item, RegexURLPattern):
|
|
28 |
if isinstance(item, URLPattern):
|
24 |
29 |
item.__class__ = DecoratedURLPattern
|
25 |
30 |
item._decorate_with = func
|
26 |
31 |
|
27 |
|
elif isinstance(item, RegexURLResolver):
|
|
32 |
elif isinstance(item, URLResolver):
|
28 |
33 |
item.__class__ = DecoratedRegexURLResolver
|
29 |
34 |
item._decorate_with = func
|
30 |
35 |
|
31 |
|
-
|