[Answered ]-Django: accessing variable value from TemplateView

1๐Ÿ‘

โœ…

I think something like this should work.

Change you urls.py to use a named view:

url(r'^path/(?P<var1>\d+)/(?P<var2>\d+)/$', YourNamedView.as_view('a_view.html'))

Create a TemplateView and let it grab your vars and add it to the context:

class YourNamedView(TemplateView):
    template_name = 'a_view.html'

    def get_context_data(self, **kwargs):
        context = super(YourNamedView, self).get_context_data(**kwargs)
        context.update({
            'var1': self.kwargs.get('var1', None),
            'var2': self.kwargs.get('var2', None),
        })
        return context

and in the template:

<h1>{{ var1 }} {{ var2 }}</h1>
๐Ÿ‘คJonas Grumann

1๐Ÿ‘

From template you can access the instance of ResolverMatch representing the resolved URL

<p>var1 value = {{ request.resolver_match.kwargs.var1 }}</p>
<p>var2 value = {{ request.resolver_match.kwargs.var2 }}</p>

Leave a comment