如何在许多基于类的视图中使用相同的上下文变量

时间:2012-10-01 16:37:50

标签: django django-views

我想在许多基于类的视图中使用相同的上下文变量,并且使用我对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

有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

像这样的mixin可能更干净:

class ContextCommonToManyViews(object):
    def get_context_data(self, request, **kwargs):
        context = super(ContextCommonToManyViews, self).get_context_data(request, **kwargs)
        context['form'] = FormForManyPages()
        context['username'] = self.request.user.username
        context['available_in_many_views'] = something
        return context

class ViewA(ContextCommonToManyViews, ListView):
    model = ModelA

class ViewB(ContextCommonToManyViews, ListView):
    model = ModelB

    def get_context_data(self, request, **kwargs):
        context = super(ViewB, self).get_context_data(request, **kwargs)
        context.update({'specific_to_B': 'some_value'})
        return context
相关问题