1

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

有没有更好的办法?

4

1 回答 1

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
于 2012-10-01T17:29:10.037 回答