加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – Django Test Client post()返回302,尽管视图的帖子()

发布时间:2020-12-16 23:26:14 所属栏目:Python 来源:网络整理
导读:我正在编写一些基本测试,以确保中等大小的Django应用程序中的页面正确获取和POST.但是,使用 django.test.client.Client不可靠地失败.即使在我的代码中存在明显的错误,它也会返回302响应. 在我的app / urls.py中: url(r'^mymodel/create/$',views.MyModelVie
我正在编写一些基本测试,以确保中等大小的Django应用程序中的页面正确获取和POST.但是,使用 django.test.client.Client不可靠地失败.即使在我的代码中存在明显的错误,它也会返回302响应.

在我的app / urls.py中:

url(r'^mymodel/create/$',views.MyModelView.as_view(),name = 'my_model_create'),

然后,为了有意创造500响应,我做了以下:

class MyModelCreateView(MyModelView,CreateView):

    def post(self,request,*args,**kwargs):
        print self.hello
        self.object = MyModel()
        return super(MyModelCreateView,self).post(request,**kwargs)

显然,该视图没有任何名为hello的对象.尝试通过浏览器发送请求时,会如预期的那样失败.

甚至更换“print self.hello”

return HttpResponse(status = 500)

然而,我仍然得到以下内容:

#We have a model called Client,so it 
#is imported as RequestClient to avoid conflicts
In [1]: from django.test.client import Client as RequestClient

In [2]: client = RequestClient()

In [3]: response = client.post("/app/mymodel/create/")

In [4]: response.status_code
Out[4]: 302

显然,这里的问题是在键盘和椅子之间,因为没有任何理由如果完成正确,Client()/ RequestClient()不应该返回500错误.即使出现一些问题,因为我收到了302个POST请求的响应,而不是200个响应,但这可能是因为我们使用HttpRedirect.

有谁在那里知道这里可能有什么问题吗?作为参考,我在Python 2.7和Django 1.5(虽然我可能需要与Django 1.4兼容).

解决方法

不完全清楚为什么你会得到一个重定向,但如果你想跟随它,你需要告诉RequestClient遵循重定向 – 每 the documentation:

If you set follow to True the client will follow any redirects and a
redirect_chain attribute will be set in the response object containing
tuples of the intermediate urls and status codes.

所以你的测试代码应该是:

Python
response = client.post(“/ app / mymodel / create /”,follow = True)

这是值得检查的请求链,以查看它在哪里路由.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读