from django.core.urlresolvers import RegexURLResolver, RegexURLPattern, Resolver404, get_resolver
__all__ = ('resolve_to_name',)
def _pattern_resolve_to_name(self, path):
match = self.regex.search(path)
if match:
name = ""
if self.name:
name = self.name
elif hasattr(self, '_callback_str'):
name = self._callback_str
else:
name = "%s.%s" % (self.callback.__module__, self.callback.func_name)
return name
def _resolver_resolve_to_name(self, path):
tried = []
match = self.regex.search(path)
if match:
new_path = path[match.end():]
for pattern in self.url_patterns:
try:
name = pattern.resolve_to_name(new_path)
except Resolver404, e:
tried.extend([(pattern.regex.pattern + ' ' + t) for t in e.args[0]['tried']])
else:
if name:
return name
tried.append(pattern.regex.pattern)
raise Resolver404, {'tried': tried, 'path': new_path}
# here goes monkeypatching
RegexURLPattern.resolve_to_name = _pattern_resolve_to_name
RegexURLResolver.resolve_to_name = _resolver_resolve_to_name
def resolve_to_name(path, urlconf=None):
return get_resolver(urlconf).resolve_to_name(path)
Comments
I just asked about this functionality yesterday in #django, not seeing it here.
Not sure why people have modded this down, but it works as advertised, and is a big help to me.
#
@Killarny: Your question in #django was what brought me to put this here.
I guess it gets downmodded b/c of the rather "ugly" mokeypatching / code duplication.
#
Neat! Had I known about this patch, it would have led to an alternate solution for the snippet that I posted here:
http://www.djangosnippets.org/snippets/1444/
#
Hi. Just what I need :o) But where do you suggest to put this code? I mean, in which files??? Thanks :o)
#
@michaelh: Where ever you like.
Personaly I put stuff like this in a seperate app so it's reusable.
#
truuuuuuuuuuuuuuuuuuuuuunk
#
This snippet is now included in django-snippetscream
#
The monkeypatching isn't necessary: http://pastebin.com/Ev0R7XkT
#
Whoops, better version
#
In Django 1.3 and newer you can use resolve function:
from django.core.urlresolvers import resolve print resolve('/books/').url_name
https://docs.djangoproject.com/en/dev/topics/http/urls/#resolve
#