为什么必须通过通用 class DetailView 的 get_context_data 方法检索上下文?
Why must context be retrieved via the get_context_data method of the generic class DetailView?
我有一个简单的问题,我会解释一下。我正在使用 djangoproject.com 上的文档阅读有关通用视图的信息,在此页面上,他们显示了以下示例:
from django.utils import timezone
from django.views.generic.detail import DetailView
from articles.models import Article
class ArticleDetailView(DetailView):
model = Article
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['now'] = timezone.now()
return context
我的问题是:当 ArticleDetailView
已经继承自 DetailView
时,为什么 context
需要通过从 super()
调用 get_context_data
方法来初始化?
您不能已经通过子类的 get_context_data 访问上下文吗?喜欢 self.get_context_data(**kwargs)
?
我很困惑!
编辑:这里是 link 文档 https://docs.djangoproject.com/en/2.2/ref/class-based-views/generic-display/
My question is: Why would context need to be initialized by calling the get_context_data
method from super()
when ArticleDetailView
is already inheriting from DetailView
? Can't you already access the context through the get_context_data
of the subclass? Like self.get_context_data(**kwargs)
?
如果您调用 self.get_context_data()
,您将调用 ArticleDetailView
的 get_context_data(..)
方法,从而调用 相同的 方法。因此,这意味着您陷入 无限递归 ,直到最终调用堆栈耗尽并且您获得 RecursionError
.
你 本身 不需要检索 super()
代理对象的上下文,例如,如果你想构建上下文字典 "from scratch".但是 DetailView
通常已经将大量数据注入到视图中。例如,它会在字典中添加一个项目 object
来引用您要显示数据的对象,并添加一个 view
来引用当时正在处理的视图实例。
我有一个简单的问题,我会解释一下。我正在使用 djangoproject.com 上的文档阅读有关通用视图的信息,在此页面上,他们显示了以下示例:
from django.utils import timezone
from django.views.generic.detail import DetailView
from articles.models import Article
class ArticleDetailView(DetailView):
model = Article
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['now'] = timezone.now()
return context
我的问题是:当 ArticleDetailView
已经继承自 DetailView
时,为什么 context
需要通过从 super()
调用 get_context_data
方法来初始化?
您不能已经通过子类的 get_context_data 访问上下文吗?喜欢 self.get_context_data(**kwargs)
?
我很困惑!
编辑:这里是 link 文档 https://docs.djangoproject.com/en/2.2/ref/class-based-views/generic-display/
My question is: Why would context need to be initialized by calling the
get_context_data
method fromsuper()
whenArticleDetailView
is already inheriting fromDetailView
? Can't you already access the context through theget_context_data
of the subclass? Likeself.get_context_data(**kwargs)
?
如果您调用 self.get_context_data()
,您将调用 ArticleDetailView
的 get_context_data(..)
方法,从而调用 相同的 方法。因此,这意味着您陷入 无限递归 ,直到最终调用堆栈耗尽并且您获得 RecursionError
.
你 本身 不需要检索 super()
代理对象的上下文,例如,如果你想构建上下文字典 "from scratch".但是 DetailView
通常已经将大量数据注入到视图中。例如,它会在字典中添加一个项目 object
来引用您要显示数据的对象,并添加一个 view
来引用当时正在处理的视图实例。