本文介绍了Django Test Client post()返回302,尽管视图的post()上出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在撰写一些基本测试,以确保中等大小的Django应用程序中的页面正确获取和POST。但是,使用django.test.client.Client不可靠地失败。即使在我的代码中显然存在错误,它也会返回302响应。

I'm currently writing up some basic tests to ensure pages in a medium sized Django application are GETting and POSTing correctly. However, using django.test.client.Client isn't reliably failing when it should be. It returns a 302 response even when there's obviously placed errors in my code.

在我的应用/ urls.py:

in my app/urls.py:

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

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

Then, in attempts to intentionally create a 500 response, I did the following:

class MyModelCreateView(MyModelView, CreateView):

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

显然,视图没有任何名为hello的对象。当尝试通过浏览器发送请求时,这样会失败。

Obviously, the view doesn't have any object called hello. This fails as expected when trying to send the request through the browser.

甚至更换print self.hello与

and even went as far as replacing "print self.hello" with

return HttpResponse(status = 500)

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

and yet, I still get the following:

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

Clearly the problem here is between the keyboard and the chair, since there's no reason Client()/RequestClient() shouldn't return a 500 error if done correctly. Even some problems arise as I receive 302 responses for POST requests instead of 200 responses, but that may be because we're using HttpRedirect.

有谁在那里知道什么可能成为这里的问题?作为参考,我在Python 2.7和Django 1.5(尽管我可能需要与Django 1.4兼容)。

Does anyone out there know what may be the problem here? For reference I'm on Python 2.7 and Django 1.5 (though I may need to be compatible with Django 1.4).

推荐答案

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

It's not totally clear why you're getting a redirect, but if you want to follow it you need to tell RequestClient to follow redirects - per the documentation:

所以你的测试代码应该如下所示:

So your test code should look like:

python
response = client.post(/ app / mymodel / create /,follow = True)

值得检查请求链,看看它在哪里路由。

It'd be worth checking the request chain to see where exactly it was routed.

这篇关于Django Test Client post()返回302,尽管视图的post()上出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 14:37