The super
方法将访问当前类并调用特定方法,在本例中:
super(ArticleDetailView, self) # Access to the current class
并执行具体方法:
.get_context_data(**kwargs)
The .get_context_data()
方法在一个View
类,返回context
传递给模板(.html
文件)。在这种情况下,您使用的是DetailView
,因此您有一些预定义的上下文,例如:object
or article
.
如果你只是覆盖.get_context_data()
不打电话.super()
, 像这样:
def get_context_data(self, **kwargs):
my_context = {...}
return my_context
您将丢失中的预定义变量DetailView
语境。但是如果你想添加一些新的变量(值)到当前DetailView
的上下文,你需要原始上下文,这就是super(ArticleDetailView, self).get_context_data(**kwargs)
会给你。所以你会这样使用它:
def get_context_data(self, **kwargs):
context = super(ArticleDetailView, self).get_context_data(**kwargs)
context.update({'my_key': 'my_value'})
return context
现在您将能够在模板中使用您自己的值,而不会丢失默认值DetailView
的上下文值。