我想在许多基于类的视图中使用相同的上下文变量,并使用我对 Python 的基本知识,我通过创建超类和使用多重继承来做到这一点:
class ContextCommonToManyViews():
def addToContext(self, context):
context['form'] = FormForManyPages()
context['username'] = self.request.user.username
context['available_in_many_views'] = something
return context
class ViewA(ListView, ContextCommonToManyViews):
model = ModelA
def get_context_data(self, **kwargs):
context = super(ViewA, self).get_context_data(**kwargs)
context = self.addToContext(context)
context['specific_to_view'] = 'ViewA here'
return context
class ViewB(ListView, ContextCommonToManyViews):
model = ModelB
def get_context_data(self, **kwargs):
context = super(ViewB, self).get_context_data(**kwargs)
context = self.addToContext(context)
context['specific_to_view'] = 'ViewB here'
return context
有没有更好的办法?