Django 请求 URL 未在此服务器上的 TestClass 中找到
Django requested URL was not found on this server in TestClass
我的测试类看起来像:
from django.test import TestCase, Client
class TestGetSomething(TestCase):
def test_get_first_url(self):
path = "some/long/path"
client = Client()
response = client.get(path=path)
self.assertEqual(response.status_code, 200)
但是 assertEquals
引发异常,404 != 200
。
当我写 print(response.__dict__)
时,我注意到请求字段:
'_closable_objects': [<WSGIRequest: GET 'somelong/path'>]
'request': {'PATH_INFO': 'some/long/path', 'REQUEST_METHOD': 'GET', 'SERVER_PORT': '80', 'wsgi.url_scheme': 'http', 'QUERY_STRING': ''}
'templates': [<django.template.base.Template object at 0x7f4b33ac17f0>], 'context': [{'True': True, 'False': False, 'None': None}, {'request_path': '/somelong/path/', 'exception': 'Resolver404'}]
如您所见,路径部分在 'some' 和 'long'
之间没有斜杠
当我尝试通过 URL 手动(使用浏览器)获取页面时,一切正常
在我的 Django 应用程序中,我只使用 Model 和 ModelAdmin。连urls.py都清楚了。
大家现在我该如何修复它?
如有必要,我会添加任何其他代码。
路径应以斜线开头/
。事实上,在您的浏览器中并没有什么不同,因为如果您写 localhost:8000/some/long/path
,第一个斜杠只是 path
的一部分。此外,浏览器通常会 "fix" a url like example.com
to example.com/
.
因此你需要这样写:
class TestGetSomething(TestCase):
def test_get_first_url(self):
# start with a slash
path = "<b>/</b>some/long/path"
client = Client()
response = client.get(path=path)
self.assertEqual(response.status_code, 200)
我的测试类看起来像:
from django.test import TestCase, Client
class TestGetSomething(TestCase):
def test_get_first_url(self):
path = "some/long/path"
client = Client()
response = client.get(path=path)
self.assertEqual(response.status_code, 200)
但是 assertEquals
引发异常,404 != 200
。
当我写 print(response.__dict__)
时,我注意到请求字段:
'_closable_objects': [<WSGIRequest: GET 'somelong/path'>]
'request': {'PATH_INFO': 'some/long/path', 'REQUEST_METHOD': 'GET', 'SERVER_PORT': '80', 'wsgi.url_scheme': 'http', 'QUERY_STRING': ''}
'templates': [<django.template.base.Template object at 0x7f4b33ac17f0>], 'context': [{'True': True, 'False': False, 'None': None}, {'request_path': '/somelong/path/', 'exception': 'Resolver404'}]
如您所见,路径部分在 'some' 和 'long'
之间没有斜杠
当我尝试通过 URL 手动(使用浏览器)获取页面时,一切正常
在我的 Django 应用程序中,我只使用 Model 和 ModelAdmin。连urls.py都清楚了。
大家现在我该如何修复它?
如有必要,我会添加任何其他代码。
路径应以斜线开头/
。事实上,在您的浏览器中并没有什么不同,因为如果您写 localhost:8000/some/long/path
,第一个斜杠只是 path
的一部分。此外,浏览器通常会 "fix" a url like example.com
to example.com/
.
因此你需要这样写:
class TestGetSomething(TestCase):
def test_get_first_url(self):
# start with a slash
path = "<b>/</b>some/long/path"
client = Client()
response = client.get(path=path)
self.assertEqual(response.status_code, 200)