[Fixed]-Extending generic view classes for common get_context_data

23👍

Create a Mixin:

from django.views.generic.base import ContextMixin

class HouseMixin(ContextMixin):
  def get_house(self):
    # Get the house somehow
    return house

  def get_context_data(self, **kwargs):
    ctx = super(HouseMixin, self).get_context_data(**kwargs)
    ctx['house'] = self.get_house()
    return ctx

Then in your other classes you’d use multiple inheritance:

class HouseEditView(HouseMixin, UpdateView):
  pass

class HouseListView(HouseMixin, ListView):
  pass

and so on, then all these views will have house in the context.

👤Jj.

Leave a comment