dabadaba
dabadaba

Reputation: 9522

Django: accessing variable value from TemplateView

Say I have the following url that maps to a TemplateView:

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

I thought in the template view a_view.html I could access the values of var1 and var2 as they're being captured and extracted into named parameters:

<!-- a_view.html -->

<p>var1 value = {{ var1 }}</p>
<p>var2 value = {{ var2 }}</p>

However, these values are blank when visiting /path/10/89. Why? How can I access them then? Would I need an explicit view?

Upvotes: 1

Views: 1331

Answers (2)

Jonas Grumann
Jonas Grumann

Reputation: 10786

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>

Upvotes: 1

Sergey Gornostaev
Sergey Gornostaev

Reputation: 7787

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>

Upvotes: 1

Related Questions