dabadaba dabadaba - 2 months ago 10
Python Question

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?

Answer

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>
Comments