我想在多个视图中放置有关一个对象的信息,而不在每个视图的 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
Run Code Online (Sandbox Code Playgroud)
它有效,但 get_context_data 不是父“视图”类的一部分。我可能需要更多特殊的类来继承 BaseObjectInfoView 吗?
或者也许更好地用另一种方法构造上下文?