簡體   English   中英

使用多個 arguments 反轉 url 時出錯 - Django

[英]Error when reverse url with multiple arguments - Django

我正在為 url 編寫測試,問題是當我嘗試通過多個 arguments 時它失敗了,這是一些代碼:

#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'

但是當只有一個參數時,測試成功。 感謝任何幫助。

您的 urlpatterns 似乎不適合接受這種格式。 嘗試以下操作:

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

測試方法只需要一個參數,那就是self ,所以你的測試 class 必須是這樣的:

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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM