为普通的get_context_data扩展通用视图类 [英] Extending generic view classes for common get_context_data

查看:286
本文介绍了为普通的get_context_data扩展通用视图类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  def get_context_data( self,** kwargs):
#首先调用基本实现来获取上下文
context = super(MyListView,self).get_context_data(** kwargs)
#在房子里添加
上下文['house'] = self.get_object()。house
返回上下文

因为我不喜欢重复自己,我以为我可以创建一个扩展视图的类,然后我可以将所有的视图都放在新的扩展视图类上。事情是,我使用了4类视图:CreateView,UpdateView,ListView和DeleteView。我真的要为其中一个创建一个新的课程吗?



没有像djangobase视图类的东西?也许是更聪明的方式来做到这一点?非常感谢提前!

解决方案

创建Mixin:

  from django.views.generic.base import ContextMixin 

class HouseMixin(ContextMixin):
def get_house(self):
#获取房子
返回房子

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


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?

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

解决方案

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.

这篇关于为普通的get_context_data扩展通用视图类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆