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

时间:2017-01-23 10:10:13

标签: python django testing django-rest-framework django-generic-views

我正在密切关注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.

我无法理解为什么会发生这种情况以及如何解决这个问题。

  • 网址中有pk个kwargs
  • 根据文档,如果默认为lookup-field,则无需明确添加pk值,
  • 视图正确打开,但此测试失败...

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

以下是相关代码:

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

2 个答案:

答案 0 :(得分:26)

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

response = view(request, pk=1)

答案 1 :(得分:0)

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

中了解为什么会出错
perform_create(self,instance):
      instance = self.get_object()