使用名为 "pk" 的 URL 关键字参数调用预期视图

Expected view to be called with a URL keyword argument named "pk"

我正在紧跟 testing documentation

为 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.

我不明白为什么会这样以及如何解决这个问题。

有人可以解释为什么会出现这个错误吗?

相关代码如下:

'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,) 

使用 URL 中的请求和参数调用视图函数。所以通过它们:

response = view(request, pk=1)

我在perform_create中错误使用get_object方法时遇到了类似的错误。从 documentation

了解错误原因
perform_create(self,instance):
      instance = self.get_object()