Django returns 403 error when sending a POST request


Question

when I'm using following Python code to send a POST request to my Django website I'm getting 403: Forbidden error.

url = 'http://www.sub.domain.com/'
values = { 'var': 'test' }

try:
    data = urllib.urlencode(values, doseq=True)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)
    the_page = response.read()
except:
    the_page = sys.exc_info()
    raise

When I'm opening any other website it works properly. domain.com is Django website too, and it works properly too. I think, that's Django config problem, can anyone tell me what should I do to provide access to my script?

1
34
9/25/2012 10:47:27 AM

Accepted Answer

Does the view that you are posting to have a Django Form on it? If so, I wonder if it's giving a csrf error. I think that manifests itself as a 403. In that case, you'd need to add the {{ csrf_token }} tag. Just a thought.

28
7/23/2011 2:58:53 PM

Look here https://docs.djangoproject.com/en/dev/ref/csrf/#how-to-use-it.

Try marking your view with @csrf_exempt. That way, Django's CSRF middleware will ignore CSRF protection. You'll also need to use from django.views.decorators.csrf import csrf_exempt. See: https://docs.djangoproject.com/en/dev/ref/csrf/#utilities

Please be advised that by disabling CSRF protection on your view, you are opening a gate for CSRF attacks.

If security is vital to you then consider using @csrf_exempt followed by @requires_csrf_token (see: https://docs.djangoproject.com/en/dev/ref/csrf/#unprotected-view-needs-the-csrf-token). Then, in your script pass this token and that's it.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon