如何使用Django中的RequestFactory将PK或slug传递给DetailView?

时间:2013-05-09 10:08:27

标签: python django unit-testing django-views

我正在尝试使用RequestFactory使用以下测试用例测试DetailView:

def test_device_homepage(self):
    request = self.factory.get('/devices/1/', {'pk': 1})

    response = DeviceView.as_view()(request)

    self.assertEqual(response.status_code, 404)

但是,当我运行上述测试时,我收到以下错误消息:

AttributeError: Generic detail view DeviceView must be called with either an object pk or a slug.

如果我在创建后打印请求,我可以看到以下内容:

<WSGIRequest
path:/devices/1/,
GET:<QueryDict: {u'pk': [u'1']}>,

据我所知,这应该是DetailView所需的全部能够超越生成上述错误消息的代码中的点。

为了完整性,完整的追溯如下:

Traceback (most recent call last):
File "/vagrant/devices/tests/test_views.py", line 17, in test_device_homepage
response = DeviceView.as_view()(request)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py", line 86, in dispatch
return handler(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/detail.py", line 108, in get
self.object = self.get_object()
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/detail.py", line 48, in get_object
% self.__class__.__name__)

1 个答案:

答案 0 :(得分:55)

感谢Freenode IRC上的#django频道,我发现以下方法是将参数一直传递到视图的正确方法:

response = DeviceView.as_view()(request, pk=1)

我希望这有助于其他人尝试使用RequestFactory来测试DetailView或DeleteView等