扩展常见get_context_data的通用视图类

时间:2022-08-29 19:22:24

I constantly see myself having to add the same extra variable to the context of many of my views.

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

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

As I don't like repeating myself, I thought I could create a new class extending the view and then I could base all my views on the new extended view class. The thing is, there are 4 classes of views I use: CreateView, UpdateView, ListView and DeleteView. Do I really have to create a new class for each of one of them?

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

Isn't there something like a django "base" view class? Maybe a smarter way to do this? Many thanks in advance!

是不是像django“基础”视图类?也许更聪明的方法呢?提前谢谢了!

1 个解决方案

#1


20  

Create a Mixin:

创建一个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.

等等,那么所有这些观点都将在上下文中占有一席之地。

#1


20  

Create a Mixin:

创建一个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.

等等,那么所有这些观点都将在上下文中占有一席之地。