Login

Resolve URLs to view name

Author:
UloPe
Posted:
March 17, 2009
Language:
Python
Version:
1.0
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

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months 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

#

Please login first before commenting.