Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I access url kwargs in django template context processor?

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 ?

like image 760
Ashish Gupta Avatar asked Feb 14 '16 13:02

Ashish Gupta


2 Answers

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 {}
like image 99
knbk Avatar answered Oct 27 '22 10:10

knbk


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

like image 24
Anupam Avatar answered Oct 27 '22 11:10

Anupam