如何在 Django 中使用 RequestFactory 将 PK 或 slug 传递给 DetailView? [英] How do I pass a PK or slug to a DetailView using RequestFactory in Django?
问题描述
我正在尝试使用 RequestFactory 使用以下测试用例测试 DetailView:
I'm trying to use RequestFactory to test a DetailView with the following test case:
def test_device_homepage(self):
request = self.factory.get('/devices/1/', {'pk': 1})
response = DeviceView.as_view()(request)
self.assertEqual(response.status_code, 404)
然而,当我运行上述测试时,我收到以下错误消息:
When I run the above test, however, I get the following error message:
AttributeError: Generic detail view DeviceView must be called with either an object pk or a slug.
如果我在创建后打印请求,我可以看到以下内容:
If I print the request after creation, I can see the following:
<WSGIRequest
path:/devices/1/,
GET:<QueryDict: {u'pk': [u'1']}>,
据我所知,这应该是 DetailView 能够越过生成上述错误消息的代码点所需的全部内容.
As far as I can tell, that should be all that the DetailView requires to be able to progress past the point in code that's generating the above error message.
为了完整起见,完整的回溯如下:
For completeness the full traceback is below:
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__)
推荐答案
感谢 Freenode IRC 上的 #django 频道,我发现以下方法是将参数一直传递到视图的正确方法:
Thanks to the #django channel on Freenode IRC, I found the following method is the correct one to pass parameters all the way through to the view:
response = DeviceView.as_view()(request, pk=1)
我希望这有助于其他人尝试使用 RequestFactory 来测试 DetailView 或 DeleteView 等
I hope this helps somebody else attempting to use RequestFactory to test DetailView or DeleteView etc
这篇关于如何在 Django 中使用 RequestFactory 将 PK 或 slug 传递给 DetailView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!