Login

Resolve URLs to view name

Author:
UloPe
Posted:
March 17, 2009
Language:
Python
Version:
1.0
Tags:
view url resolve name
Score:
4 (after 6 ratings)

This snippet suplies a resolve_to_name function that takes in a path and resolves it to a view name or view function name (given that the path is actually defined in your urlconf).

Example:

=== urlconf ====
urlpatterns = patterns(''
    (r'/some/url', 'app.views.view'),
    (r'/some/other/url', 'app.views.other.view', {}, 'this_is_a_named_view'),
)

=== example usage in interpreter ===
>>> from some.where import resolve_to_name
>>> print resolve_to_name('/some/url')
'app.views.view'
>>> print resolve_to_name('/some/other/url')
'this_is_a_named_view'
 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

Comments

Killarny (on March 19, 2009):
<p>I just asked about this functionality yesterday in #django, not seeing it here.</p> <p>Not sure why people have modded this down, but it works as advertised, and is a big help to me.</p>

#

UloPe (on March 23, 2009):
<p>@Killarny: Your question in #django was what brought me to put this here.</p> <p>I guess it gets downmodded b/c of the rather "ugly" mokeypatching / code duplication.</p>

#

michaelh (on August 27, 2009):
<p>Hi. Just what I need :o) But where do you suggest to put this code? I mean, in which files??? Thanks :o)</p>

#

UloPe (on August 28, 2009):
<p>@michaelh: Where ever you like.</p> <p>Personaly I put stuff like this in a seperate app so it's reusable.</p>

#

yeago (on July 20, 2010):
<p>truuuuuuuuuuuuuuuuuuuuuunk</p>

#

majgis (on August 8, 2012):
<p>In Django 1.3 and newer you can use resolve function:</p> <p>from django.core.urlresolvers import resolve print resolve('/books/').url_name</p> <p>https://docs.djangoproject.com/en/dev/topics/http/urls/#resolve</p>

#

Please login first before commenting.