我正在密切关注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,)
答案 0 :(得分:26)
使用请求和URL中的参数调用视图函数。通过他们:
response = view(request, pk=1)
答案 1 :(得分:0)
当我在perform_create中使用get_object方法出错时,遇到了类似的错误。从documentation
中了解为什么会出错perform_create(self,instance):
instance = self.get_object()