views:

196

answers:

1

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.

+1  A: 

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,

Boldewyn
+1 This is exactly what view middleware is for. If you don't like stuffing the full request object into all your templates, you can still pair view middleware with your own context processor that pulls the value off the request object and puts it directly in the context.
Carl Meyer
I have tried doing the above but the view_kwargs dict doesn't have the key 'name'. Are you sure the URL name ends up in the dict?
atharh
try rewriting it as a dict: {'name': 'website.home'} in urls.py
Boldewyn
Sure this would work but then all my views would have to accept an additional argument. Also, IMHO, this sort of goes against the spirit of DRY since my URL patterns will look like: url(r'^home/$', 'app.index', {'name': 'website.home'}, name='website.home')I also need reverse('website.home') to work.
atharh