Django passing variables to templates from class based views

前端 未结 4 1128
太阳男子
太阳男子 2020-12-09 08:59

If I have a class based view, like this,

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

    def get(self, re         


        
4条回答
  •  盖世英雄少女心
    2020-12-09 09:38

    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.

提交回复
热议问题