Search code examples
djangoinheritancedjango-viewsmixins

Django CBV's: Custom mixin's that override the same method of one View


I have the following CBV with custom mixins, AjaxFormMixin_Home and AjaxFormMixin_Production.

# app1/views.py
class BaseView(AjaxFormMixin_Home, AjaxFormMixin_Production, FormMixin, View):

Based on certain ajax conditions, both mixins override def get_context_data(self, **kwargs): as required by FormMixin. See below,

# app1/mixins.py
class AjaxFormMixin_Home(ContextMixin, object):

   def get_context_data(self, **kwargs):
       context = super(AjaxFormMixin_Home, self).get_context_data(**kwargs)
       obj = UserNote.objects.all()
       paginatedObject_Home = Paginator(obj, 5)
       page = self.request.GET.get('userNotepage')
       context.update('paginatedObject_Home':paginatedObject_Home.page(page))
       return context

# app2/mixins.py
class AjaxFormMixin_Production(ContextMixin, object):

   def get_context_data(self, **kwargs):
       context = super(AjaxFormMixin_Production, self).get_context_data(**kwargs)
       obj = Production.objects.all()
       paginatedObject_Production = Paginator(obj, 5)
       page = self.request.GET.get('productionPage')
       context.update('paginatedObject_Production':paginatedObject_Production.page(page))
       return context

Now, this is the problem. Changing the order of inheritance in BaseView only returns the context as defined by that particular mixin. I need to return both paginatedObject_Home and paginatedObject_Production to BaseView.

For instance,

  1. Below will only return context as defined by AjaxFormMixin_Home

    class BaseView(AjaxFormMixin_Home, AjaxFormMixin_Production, FormMixin, View):

  2. Whereas below will only return context as defined by AjaxFormMixin_Production

    class BaseView(AjaxFormMixin_Production, AjaxFormMixin_Home, FormMixin, View):

Lastly, I've noticed the compiler ignores the second mixin altogether (depending on order of inheritance).

How can does one get around this type of issue?

Thanks!


Solution

  • Thank you Daniel for your contribution, and for also pointing out naming convensions improvements. Would appreciate if you let me know how the code deviated from best practice as I am self taught.

    Thank you Alasdair for pointing out the issue with Form submission and validation.

    I solved the problem not by changing super call to get_context_data, but by changing the naming convention of methods within each mixin. The reason the context data was not updating correctly seems to be because,

    1. BaseView inherits both mixins. And GET calls to it were making reference to duplicate method names even with vastly different functionality.
      1. Alasdair, as you correctly pointed out, form validation was an issue because of same method names for each mixin.

    Thanks for your time guys!