atharh
atharh

Reputation: 31

Get name for matched URL pattern

I am writing a Django context processor which needs to access the name of the URL pattern that the request got successfully resolved against. Given the pattern,

url(r'^home/$', 'app.index', name='website.home')

and the request path /home, I want to get the value for name, which in this case is website.home.

I got this code from djangosnippets.org:

def _get_named_patterns():
    """ Returns a list of (pattern-name, pattern) tuples.
    """
    resolver = urlresolvers.get_resolver(None)
    patterns = sorted(
        (key, val[0][0][0]) for key, val in resolver.reverse_dict.iteritems() if isinstance(key, basestring))
    return patterns

I can use this to achieve my objective but my gut feeling says that there has to be a better method. Thanks for the help.

Upvotes: 1

Views: 2183

Answers (1)

Boldewyn
Boldewyn

Reputation: 82734

What about doing it via the request object and a middleware? Like:

class MyMiddleware (object):
  def process_view (self, request, view_func, view_args, view_kwargs):
    if view_kwargs.get ('name', None):
      request.name = view_kwargs.get ('name', None)
    ret None

and using the default context preprocessor in settings.py:

"django.core.context_processors.request",

Then you can get the name via request.name everywhere after the middleware is executed.

Cheers,

Upvotes: 1

Related Questions