简体   繁体   中英

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 ?

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 {}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM