我是Django的新手。我想使用mixin将某些数据返回到多个基于类的视图。看来我在mixin中定义的get_context_data
在视图类中没有被调用。
class MyMixin(object):
def get_context_data(self, *args, **kwargs):
data = super(MyMixin, self).get_context_data(*args, **kwargs)
from django.utils import timezone
data['object'].now = timezone.now()
return data
class PageDetail(DetailView, MyMixin):
model = MyModel
template_name = 'page-detail.html'
def get_context_data(self, *args, **kwargs):
data = super(PageDetail, self).get_context_data(*args, **kwargs)
return data
答案 0 :(得分:2)
您以错误的顺序定义基类:
class PageDetail(DetailView, MyMixin):
# ...
表示method resolution order (MRO)被定义为:
>>> PageDetail.__mro__
(<class 'PageDetail'>,
<class 'django.views.generic.detail.DetailView'>,
<class 'django.views.generic.detail.SingleObjectTemplateResponseMixin'>,
<class 'django.views.generic.base.TemplateResponseMixin'>,
<class 'django.views.generic.detail.BaseDetailView'>,
<class 'django.views.generic.detail.SingleObjectMixin'>,
<class 'django.views.generic.base.ContextMixin'>,
<class 'django.views.generic.base.View'>,
<class 'MyMixin'>,
<class 'object'>)
因此,这意味着如果我们遵循super(PageDetail, self).get_context_data(*args, **kwargs)
,它将永远不会到达MyMixin
,因为ContextMixin
将其定义为:
class ContextMixin: def get_context_data(self, **kwargs): if 'view' not in kwargs: kwargs['view'] = self if self.extra_context is not None: kwargs.update(self.extra_context) return kwargs
,因此不调用任何super()
方法。
您应将PageDetail
定义为:
class PageDetail(MyMixin, DetailView):
# ...
所以现在MRO定义为:
>>> PageDetail.__mro__
(<class 'PageDetail'>,
<class 'MyMixin'>,
<class 'django.views.generic.detail.DetailView'>,
<class 'django.views.generic.detail.SingleObjectTemplateResponseMixin'>,
<class 'django.views.generic.base.TemplateResponseMixin'>,
<class 'django.views.generic.detail.BaseDetailView'>,
<class 'django.views.generic.detail.SingleObjectMixin'>,
<class 'django.views.generic.base.ContextMixin'>,
<class 'django.views.generic.base.View'>,
<class 'object'>)
,因此super(PageDetail, self).get_context_data(*args, **kwargs)
将调用get_context_data
类的MyMixin
,然后该类将在MRO中调用下一个方法。