, views_search.index, name='ar...">

Can I access the kwargs url in the django template context handler?

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 run it, it prints an empty dict and returns nothing to the template. I added this to the template context processors in the setup. How can I access kwargs here?

+4
source share
2 answers

If the URL is allowed, the object is ResolverMatchset as a request attribute:

def get_username(request):
    if hasattr(request, 'resolver_match'):
        slug = request.resolver_match.kwargs.get('slug')
        return {'slug': slug}
    return {}
+4
source

Actually, for classes based on the class, it is viewalready available in context, so you can directly access the kwargstemplate. In the template, simply follow these steps:

{{ view.kwargs.slug }}

. SO

0

Source: https://habr.com/ru/post/1628714/


All Articles