预期视图被调用时需要使用名为“pk”的URL关键字参数。

32

我正在编写Django Rest Framework视图的测试,紧密遵循测试文档

这是我的简单测试:

def test_patient_detail_api_opens(self):
    factory = APIRequestFactory()
    view =PatientDetailApi.as_view()
    request = factory.get(reverse('api_pacjent', kwargs={'pk' :1}))
    force_authenticate(request, user=self.user)
    response = view(request)
    self.assertEqual(response.status_code, 200)

这个测试失败并显示以下信息:

AssertionError: Expected view PatientDetailApi to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly.

我不明白为什么会发生这种情况以及如何修复它。

  • URL中存在pk kwargs,
  • 根据文档,如果lookup-field默认为pk,则无需显式添加其值,
  • 视图正确打开,但是此测试失败...

请问有人能解释一下为什么会出现这个错误吗?

以下是相关代码:

'main' url.py

urlpatterns = [
    url(r'^pacjent/', include('pacjent.urls')),
] 

pacjent.urls看起来是这样的:

url(r'^api/szczegoly/(?P<pk>\d+)/$', PatientDetailApi.as_view(), name="api_pacjent"),

PatientDetailApi 就是这个:

class PatientDetailApi(generics.RetrieveUpdateAPIView):
    model = Patient
    serializer_class = PatientDetailsSerializer
    queryset = Patient.objects.all()

    authentication_classes = (SessionAuthentication, BasicAuthentication)
    permission_classes = (IsAuthenticated,) 

当你在测试之外实际请求API时,例如通过Postman,它是否有效?或者如果你使用APIClient呢? - Daniel Roseman
是的,正是如此。这正是RemcoGerlich提到的缺失部分。感谢您的建议! - user1544500
如果您在Postman中使用命名参数调用API,API端点将是什么? @user1544500 - Asad Manzoor
2个回答

53

视图函数使用来自URL的请求和参数进行调用。因此,请将它们传递:

response = view(request, pk=1)

天啊,我试图将它添加到as_view,然后是factory.get,接着又尝试着玩弄请求本身... - Csaba Toth

7

当我在perform_create中误使用 get_object 方法时,遇到了类似的错误。从文档了解这个错误的原因。

perform_create(self,instance):
      instance = self.get_object()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接