django - 为通用 get_context_data 扩展通用 View 类

标签 django django-generic-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
由于我不喜欢重复自己,我想我可以创建一个扩展 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/

相关文章:

python - 在表单集中设置 auto_id 并且不要在首次显示时禁用错误

python - 如何统计与ListView中显示的项目相关的对象?

python - Django/Celery - AttributeError : module 'novopagemento' has no attribute 'celery'

django - FreeTDS SQL Server 无效的数据类型

django - 如何将数据添加到 DetailView 中的上下文对象?

python - 在 ListView 中使用 get_context_Data 进行 paginate_by 时,页面显示所有行

python - 在 django urls.py 中访问请求对象

python - djangorest框架中django过滤器后端的条件?

python - 使用空白电子邮件添加多个 Django 用户