使用多个参数反转url时出错-Django



我正在为一个url编写一个测试,问题是当我试图传递多个参数时它失败了,下面是一些代码:

#test_urls.py
from django.test import SimpleTestCase
from django.urls import reverse, resolve
from cardiotesting.views import *
class TestUrls(SimpleTestCase):
def test_new_cardio(id_patient, protocol):
id_patient = '05'
protocol = 'fox'
url = reverse('new_cardio_testing', args=[id_patient, protocol])
print(resolve(url))
#urls.py
from django.urls import path
from . import views
urlpatterns = [
path('new/<str:id_patient>', views.new_cardio_testing, name='new_cardio_testing'),
]
#views.py
def new_cardio_testing(id_patient, protocol):
pass

当我运行测试时,它返回:

.E
======================================================================
ERROR: test_new_cardio_testing (cardiotesting.tests.test_urls.TestUrls)
----------------------------------------------------------------------
TypeError: TestUrls.test_new_cardio_testing() missing 1 required positional argument: 'protocol'

但当只有一个论点时,测试就成功了。

您的url模式似乎不适合接受这种格式。尝试以下操作:

urlpatterns = [
path('new/<str:id_patient>/<str:protocol>/', views.new_cardio_testing, name='new_cardio_testing'),
# Django loves it's trailing slashes.
]

测试方法只需要一个参数,那就是self,所以你的测试类必须是这样的:

class TestUrls(SimpleTestCase):
def test_new_cardio(self):
id_patient = '05'
protocol = 'fox'
url = reverse('new_cardio_testing', args=[id_patient, protocol])
print(resolve(url))

最新更新