1

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?

1
  • 1
    Everything seems fine to me. You can use context.update(self.addToContext()) instead of context = self.addToContext(context). Commented Oct 1, 2012 at 17:09

1 Answer 1

1

A mixin like this might be cleaner:

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
Sign up to request clarification or add additional context in comments.

4 Comments

It does look cleaner. Is there a way to do context['specific_to_view'] = 'ViewB here'?
sorry should have made that requirement clearer in the question
There is. In ViewB define get_context_data(), call it with super and update with 'specific_to_view' value
Just as @DimaBildin says. I've updated the answer with an example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.