Resolve URLs to view name

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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)

More like this

  1. Resolve URLs to view name and args/kwargs by fahhem 3 years, 5 months ago
  2. django subdomain support for both resolve and reverse. by puppy 3 years, 10 months ago
  3. Database Routing by URL by dcwatson 3 years, 10 months ago
  4. Url filter middleware by limodou 7 years, 1 month ago
  5. A action decorator for URLs by Batiste 6 years ago

Comments

Killarny (on March 19, 2009):

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.

#

UloPe (on March 23, 2009):

@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.

#

michaelh (on August 27, 2009):

Hi. Just what I need :o) But where do you suggest to put this code? I mean, in which files??? Thanks :o)

#

UloPe (on August 28, 2009):

@michaelh: Where ever you like.

Personaly I put stuff like this in a seperate app so it's reusable.

#

yeago (on July 20, 2010):

truuuuuuuuuuuuuuuuuuuuuunk

#

majgis (on August 8, 2012):

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

#

(Forgotten your password?)