【问题标题】:Django requested URL was not found on this server in TestClass在 TestClass 中的此服务器上找不到 Django 请求的 URL
【发布时间】:2018-06-08 17:32:02
【问题描述】:

我的 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 也很清楚。
大家现在我该如何解决它?
如有必要,我将添加任何其他代码。

【问题讨论】:

  • urls.py 是什么?有效的路径是什么?
  • 您可能需要在此处添加前导斜杠。

标签: django django-testing django-tests


【解决方案1】:

路径应以斜杠 / 开头。事实上在你的浏览器中也没有什么不同,因为如果你写localhost:8000/some/long/path,第一个斜线只是path的一部分。此外,浏览器通常会将example.com 之类的网址“修复”为example.com/

因此你需要这样写:

class TestGetSomething(TestCase):

    def test_get_first_url(self):
        # start with a slash
        path = "/some/long/path"
        client = Client()
        response = client.get(path=path)
        self.assertEqual(response.status_code, 200)

【讨论】:

    猜你喜欢
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 2017-03-21
    • 2010-10-16
    • 1970-01-01
    • 2017-12-26
    • 2015-03-30
    相关资源
    最近更新 更多