gpt4 book ai didi

django - 未调用 mixin 中的 get_context_data

转载 作者:行者123 更新时间:2023-12-02 03:27:20 26 4
gpt4 key购买 nike

我是 Django 的新手。我想使用 mixin 将一些数据返回到多个基于类的 View 。我在 mixin 中定义的 get_context_data 似乎没有在 View 类中调用。

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

最佳答案

您以错误的顺序定义基类:

class PageDetail(<b><s>DetailView, MyMixin</s></b>):
# ...

表示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(<b>MyMixin, DetailView</b>):
# ...

所以现在 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) 将调用 MyMixinget_context_data类,然后它将调用 MRO 中的 next 方法。

关于django - 未调用 mixin 中的 get_context_data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52914262/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com