结合MultipleObjectMixin和FormView

时间:2016-08-01 11:00:45

标签: django

我在Django中使用基于类的视图,该视图继承自MultipleObjectMixinFormView。代码是这样的:

class UnseenActivityView(MultipleObjectMixin, FormView):
    form_class = UnseenActivityForm
    template_name = "user_unseen_activity.html"
    paginate_by = 20

    def get_queryset(self):
        queryset = #some queryset       
        return queryset

    def get_context_data(self, **kwargs):
        context = super(UnseenActivityView, self).get_context_data(**kwargs)
        if self.request.user.is_authenticated():
            context["verified"] = VERIFIED_USERS #this is a list of special IDs 
        return context

这段代码为keyerror返回u'object_list'。似乎object_list在kwargs字典中不存在。有人可以帮我解决这个问题吗?我的cbv需要FormView,但是需要分页,因此将其与MultipleObjectMixin合并。

Traceback (most recent call last):
  File "/home/hassan/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "/home/hassan/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 25, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/home/hassan/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/hassan/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/views/generic/base.py", line 86, in dispatch
    return handler(request, *args, **kwargs)
  File "/home/hassan/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/views/generic/edit.py", line 155, in get
    return self.render_to_response(self.get_context_data(form=form))
  File "/home/hassan/Desktop/myproject/myapp/views.py", line 5494, in get_context_data
    context = super(UnseenActivityView, self).get_context_data(**kwargs)
  File "/home/hassan/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/views/generic/list.py", line 95, in get_context_data
    queryset = kwargs.pop('object_list')
KeyError: u'object_list'

1 个答案:

答案 0 :(得分:2)

这种方法会遇到问题。

Python使用method resolution order来确定父类的哪个方法被调用。在您的情况下,super(UnseenActivityView, self).get_context_data()会调用MultipleObjectMixin.get_context_data,但不调用FormView.get_context_data。无论哪种方式,您都不会最终将两个父类的上下文传递给您的模板,并且某些内容会中断。

这也是您获得KeyError - MultipleObjectMixin.get_context_data期望object_list kwarg,但未提供{0}}的原因,因为get()方法通常调用get_context_data()来自FormView(方法解决方案),它不知道任何object_list

我建议您以这种方式组合这些类,并注意advice in the documentation

  

通用视图将有一个限制。如果您发现自己正在努力将视图实现为通用视图的子类,那么您可能会发现使用您自己的基于类或功能的视图编写所需的代码会更有效。

在这种情况下,我建议您使用FormView来处理您的表单,但是编写代码来自行处理列表视图,而不是尝试插入MultipleObjectMixin。您当然可以从MultipleObjectMixin复制逻辑。