8
urls.py

url(r'^(?i)(?P<slug>[a-zA-Z0-9_]+)$', views_search.index, name='articles'),

context_processor.py

def get_username(request, **kwargs):
    print kwargs
    slug = kwargs.get('slug')
    return {
    'slug': slug
    }

But when i am running it, its printing empty dict and nothing is returned to the template. I have added this in template context processors in setting. How can I access kwargs here ?

Ashish Gupta
  • 2,574
  • 2
  • 29
  • 58
  • Why would you want to do that? The url kwargs are specific to the view. So why not just add them to the context there? – user2390182 Feb 14 '16 at 15:14

2 Answers2

11

If an url is resolved, the ResolverMatch object is set as an attribute on the request:

def get_username(request):
    if hasattr(request, 'resolver_match'):
        slug = request.resolver_match.kwargs.get('slug')
        return {'slug': slug}
    return {}
knbk
  • 52,111
  • 9
  • 124
  • 122
3

Actually, for class based views, the view is already available in the context, so you can directly access kwargs in the template. In the template, just do the following:

{{ view.kwargs.slug }}

Also, see this SO answer

Anupam
  • 14,950
  • 19
  • 67
  • 94