1

I just started to shift from function-based views to class-based views, as I realize more and more the benefits of the latter, especially regarding the modularity that you can achieve via mixins.

However, as CBVs and Mixins are still quite new to me, I wanted to check, if I understand the basic concepts correctly:

Example:

class ReportingMixin1(object):

     def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        context['reportingmixin1_context']  = 'test1'

        return context


class ReportingMixin2(object):

     def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        context['reportingmixin2_context']  = 'test2'

        return context


class MyTemplateView(ReportingMixin1, ReportingMixin2, TemplateView):

    template_name = 'test4.html'

My questions are the following:

  1. With function based views I would do context = {'reportingmixin1': 'test1} but I see that with class based views this is always done via context['reportingmixin1'] = 'test1 . Why is this the case? I assume one reason is that when combining multiple mixins in a TemplateView (as in the code in my example) but with context = {'reportingmixin1': 'test1} and context = {'reportingmixin2': 'test2} I would initiate or redefine the context dictionary in each mixin, so you would have only access to the context keys I defined in my mixin that is called last?
  2. What is context = super().get_context_data(**kwargs) doing exactly? I read that it is "calling the base implementation first to get a context" - but what does that mean exactly?
  3. When I combine multiple Mixins in my Template view in the way shown in my code example in MyTemplateView , I can access all the context keys in my template form all my mixins, correct?
Daniel
  • 963
  • 1
  • 12
  • 29
  • I would recommend going through the [**super()**](https://stackoverflow.com/questions/222877/what-does-super-do-in-python) method and [**method resolution order**](https://stackoverflow.com/questions/3634211/python-3-1-c3-method-resolution-order) to understand these Django concepts – JPG Apr 27 '20 at 09:20
  • 1
    Unrelated but I've been using Django on dozen projects since the 0.9x days, and unless you have a use case for view inheritance (which is most often not the case) I fail to see _any_ "benefit" from using CBVs - unless you consider that turning simple straightforward self-contained code into a mess of useless indirections to half a dozen base and mixin classes defined (and documented) in different places to be a "benefit" of course. – bruno desthuilliers Apr 27 '20 at 09:23
  • 1
    @ArakkalAbu "these Django concepts" are actually just plain _Python_ concepts ;-) (but I totally agree with you on the advice). – bruno desthuilliers Apr 27 '20 at 09:36

0 Answers0