期望将视图调用为带有名为"pk"的URL关键字参数

2024-05-17 19:44:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为Django Rest框架视图编写一个测试,紧跟着testing documentation

下面是我的简单测试:

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中有pkkwargs
  • 根据文档,如果默认值为pk,则无需显式添加lookup-field
  • 视图正确打开,但此测试失败。。。

有人能解释一下为什么会发生这个错误吗?

以下是相关代码:

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

Tags: theselfview视图apiurlresponserequest
2条回答

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

response = view(request, pk=1)

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

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

相关问题 更多 >