سؤال

I'm using Django 1.6 and python 3.3.

I'm trying to test POST form with django test client, and it receives 403 after sending request. If I add @csrf_exempt at my view method, everything works perfect. But the Django documentation says that it should work with enabled csrf protection fine:

For this reason, Django’s HTTP client for tests has been modified to set a flag on requests which relaxes the middleware and the csrf_protect decorator so that they no longer rejects requests.

Here is my test code:

def testSimple(self):
    c = Client('Chrome 1.0')
    from partners.views import cashier
    response = c.post(reverse(cashier.simple), {'x': 123})
    self.assertContains(response,'html')

And here is a view:

def simple(request):
    return render(request, 'partners/cashier/index.html')

And when I run this test I see:

AssertionError: 403 != 200

So, can you please tell me what I'm doing wrong?

هل كانت مفيدة؟

المحلول

Client() has the following __init__:

def __init__(self, enforce_csrf_checks=False, **defaults):

You're setting enforce_csrf_checks to True b/c 'Chrome 1.0' evaluates to truthy!

If you want to set the user agent:

c = Client(HTTP_USER_AGENT='Mozilla/5.0')

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top