django 测试客户端获取 404,但浏览器工作
django test client gets 404, but browser works
我可以通过网络浏览器 (http://127.0.0.1:8983/solr
) 访问本地地址以查看 Solr Admin(搜索 webapp)。
但是,通过 Django (1.7) 测试客户端我得到:
>>> from django.test import Client
>>> c = Client()
>>> response = c.get('http://127.0.0.1:8983/solr')
>>> response.status_code
404
为什么 Django 无法连接到与我的浏览器相同的地址?
您应该提供 相对 URL 到 get()
:
c.get("/solr/")
这记录在 Testing Tools 页:
When retrieving pages, remember to specify the path of the URL, not
the whole domain. For example, this is correct:
c.get('/login/')
This is incorrect:
c.get('http://www.example.com/login/')
添加到@alecxe 的,你应该指定相对的url;最好的做法是使用 reverse()
来获得 url:
from django.core.urlresolvers import reverse
from django.test import Client
c = Client()
# assuming you've named the route 'solar'
url = reverse('solar')
c.get(url)
我可以通过网络浏览器 (http://127.0.0.1:8983/solr
) 访问本地地址以查看 Solr Admin(搜索 webapp)。
但是,通过 Django (1.7) 测试客户端我得到:
>>> from django.test import Client >>> c = Client() >>> response = c.get('http://127.0.0.1:8983/solr') >>> response.status_code 404
为什么 Django 无法连接到与我的浏览器相同的地址?
您应该提供 相对 URL 到 get()
:
c.get("/solr/")
这记录在 Testing Tools 页:
When retrieving pages, remember to specify the path of the URL, not the whole domain. For example, this is correct:
c.get('/login/')
This is incorrect:
c.get('http://www.example.com/login/')
添加到@alecxe 的reverse()
来获得 url:
from django.core.urlresolvers import reverse
from django.test import Client
c = Client()
# assuming you've named the route 'solar'
url = reverse('solar')
c.get(url)