Django passing variables to templates from class based views

前端 未结 4 1130
太阳男子
太阳男子 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 09:26

    For passing your class label variable inside a function, you need to refer with self which refer as a newly created object. As we know for accessing any variable in class we need to refer to its object. Otherwise, it will be caught global name 'your variable' is not defined

    as an example in your case you can do it like

    class YourView(genericView):
        template_name='your_template.html'
        var1 = 12
        var2 =1
    
        def get(self, **kwargs):
            context = locals()
            context['var1'] = self.var1
           context['var2'] = self.var2
           return context
    

提交回复
热议问题