17

我经常看到自己不得不在我的许多观点的上下文中添加相同的额外变量。

def get_context_data(self, **kwargs):
    # Call the base implementation first to get a context
    context = super(MyListView, self).get_context_data(**kwargs)
    # Add in the house
    context['house'] = self.get_object().house
    return context

由于我不喜欢重复自己,我想我可以创建一个扩展视图的新类,然后我可以将所有视图基于新的扩展视图类。问题是,我使用了 4 类视图:CreateView、UpdateView、ListView 和 DeleteView。我真的必须为每个人创建一个新课程吗?

没有像 Django“基础”视图类之类的东西吗?也许更聪明的方法可以做到这一点?

4

1 回答 1

21

创建一个混合:

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

然后在您的其他类中,您将使用多重继承:

class HouseEditView(HouseMixin, UpdateView):
  pass

class HouseListView(HouseMixin, ListView):
  pass

依此类推,那么所有这些观点都会house在上下文中产生。

于 2012-04-26T18:04:03.837 回答