dabadaba dabadaba - 1 year ago 51
Python Question

Django: accessing variable value from TemplateView

Say I have the following url that maps to a


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

I thought in the template view
I could access the values of
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
. Why? How can I access them then? Would I need an explicit view?

Answer Source

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)
            'var1': self.kwargs.get('var1', None),
            'var2': self.kwargs.get('var2', None),
        return context

and in the template:

<h1>{{ var1 }} {{ var2 }}</h1>