I'd like use the same context variables in a number of class-based views, and using my rudimentary knowledge of Python I've done this by making a superclass and using multiple inheritance:
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
Is there a better way?
context.update(self.addToContext())instead ofcontext = self.addToContext(context).