我经常看到自己不得不在我的许多观点的上下文中添加相同的额外变量。
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
由于我不喜欢重复自己,我想我可以创建一个扩展 View 的新类,然后我可以将所有 View 基于新的扩展 View 类。问题是,我使用了 4 类 View :CreateView、UpdateView、ListView 和 DeleteView。我真的必须为每个人创建一个新类(class)吗?没有像 Django“基础” View 类之类的东西吗?也许更聪明的方法可以做到这一点?
最佳答案
创建一个混合:
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
以此类推,那么所有这些 View 都会有
house
在上下文中。
关于django - 为通用 get_context_data 扩展通用 View 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10337290/