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

use*_*500 18 python testing django django-generic-views django-rest-framework

我正在密切关注测试文档,为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)
Run Code Online (Sandbox Code Playgroud)

此测试失败,并显示以下消息:

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.
Run Code Online (Sandbox Code Playgroud)

我不明白为什么会发生这种情况以及如何解决这个问题.

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

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

这是相关的代码:

'主' url.py:

urlpatterns = [
    url(r'^pacjent/', include('pacjent.urls')),
] 
Run Code Online (Sandbox Code Playgroud)

pacjent.urls 看起来像这样:

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

而且PatientDetailApi是这样的:

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

    authentication_classes = (SessionAuthentication, BasicAuthentication)
    permission_classes = (IsAuthenticated,) 
Run Code Online (Sandbox Code Playgroud)

Rem*_*ich 30

使用请求和URL中的参数调用视图函数.通过他们:

response = view(request, pk=1)
Run Code Online (Sandbox Code Playgroud)


7gu*_*uyo 6

我在perform_create中使用get_object方法出错时遇到了类似的错误。从文档中阅读为什么会出错

perform_create(self,instance):
      instance = self.get_object()
Run Code Online (Sandbox Code Playgroud)