【发布时间】:2017-11-28 01:54:07
【问题描述】:
我想将一个对象的信息放在多个视图中,而不在每个视图的 get_context_data 中重复。如您所知,我需要一个内部带有 get_context_data 的类,我可以与其他视图混合使用。 在我的示例中,我想在 UpdateAnotherObjectView 的上下文中查看“some_object”:
class BaseObjectInfoView(View):
def get_context_data(self, **kwargs):
context_data = super(BaseObjectInfoView, self).get_context_data(**kwargs)
context_data['some_object'] = SomeObjects.objects.get(pk=1)
return context_data
class UpdateAnotherObjectView(BaseObjectInfo, UpdateView):
template_name = 'create_object.html'
form_class = AnotherObjectForm
model = AnotherObjects
def get_context_data(self, **kwargs):
context_data = super(UpdateAnotherObjectView, self).get_context_data(**kwargs)
context_data['all_another_objects'] = AnotherObjects.objects.all()
return context_data
它有效,但 get_context_data 不是父“视图”类的一部分。可能我需要更多特殊的类来继承 BaseObjectInfoView 吗?
或者用另一种方法构建上下文可能更好?
【问题讨论】: