Django passing variables to templates from class based views

前端 未结 4 1095
太阳男子
太阳男子 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:28

    There are two approaches as you can see here. The first one, you can declare a function named get_context_data like this:

    def get_context_data(self, **kwargs):          
        context = super().get_context_data(**kwargs)                     
        new_context_entry = "here it goes"
        context["new_context_entry"] = new_context_entry
        return context
    

    If you are using Django 2.x you must pass *args in get_context_data too.

    The second approach is modifying extra_context variable in some function in the view:

    self.extra_context["another_one"] = "here goes more"
    

提交回复
热议问题