Search code examples
djangoclassdjango-templatesdjango-viewsdjango-class-based-views

Django passing variables to templates from class based views


If I have a class based view, like this,

class SomeView (View):
    response_template='some_template.html'
    var1 = 0
    var2 = 1

    def get(self, request, *args, **kwargs):
        return render_to_response(self.response_template, locals(), context_instance=RequestContext(request))

My question is, inside the template some_template.html, how do I access var1 and var2? As far as I understood this, the locals() sort of just dumps all the local variables into the template, which has worked very well so far. But these other variables aren't technically "local", they're part of a class, so how do I pass them over??

Thanks!


Solution

  • Add self.var1 and self.var2 to the context in get method:

    class SomeView (View):
        response_template='some_template.html'
        var1 = 0
        var2 = 1
    
        def get(self, request, *args, **kwargs):
            context = locals()
            context['var1'] = self.var1
            context['var2'] = self.var2
            return render_to_response(self.response_template, context, context_instance=RequestContext(request))
    

    Note: render_to_response() is removed in Django 3.0 and above (use render() instead).

    Also, I'm not sure that passing locals() as a context to the template is a good practice. I prefer to construct the data passed into the template explicitly = pass only what you really need in the template.