Suhas Shelar
Suhas Shelar

Reputation: 983

Sending POST request with JSON data in DJANGO and response from view also JSON data but its giving 403 FORBIDDEN error

I am trying to send a POST request to Django with JSON data in it and the view is returning response with JSON data. But when I send a request to it, it returns with 403 Forbidden error. I am using RESTClient to send/test POST requests.

I have read all about CSRF in documentation but its not very helpful. I am fairly new to Django and the other questions posted here are not helping me a lot.

The code in my view is:

from django.shortcuts import render
from django.http import HttpResponse;
import json;
def index(request):
        if request.is_ajax():
            if request.method == 'POST':
                print 'Raw Data: "%s"' % request.body;
                reply = json.loads(request.body);
                return HttpResponse(reply);
            else:
                return HttpResponse("OK");

        else:
            return HttpResponse("OK");

Upvotes: 1

Views: 1742

Answers (2)

Ernest
Ernest

Reputation: 2949

In addition to @ArpitGoyal's answer you can also decorate your view with csrf_exempt:

This decorator marks a view as being exempt from the protection ensured by the middleware.

A few tips in case you do need CSRF protection:

  1. Check CSRF token cookie name.

    See CSRF_COOKIE_NAME for more information.

  2. Add ensure_csrf_cookie decorator to your view.

    According to the docs:

    Warning

    If your view is not rendering a template containing the csrf_token template tag, Django might not set the CSRF token cookie. This is common in cases where forms are dynamically added to the page. To address this case, Django provides a view decorator which forces setting of the cookie: ensure_csrf_cookie().

  3. Assuming that CSRF token cookie name is csrftoken, try to send X-CSRFToken header.

    $.ajax({
        // Your options here.
        headers: {'X-CSRFToken': getCookie('csrftoken')}
    });
    

Upvotes: 1

Arpit Goyal
Arpit Goyal

Reputation: 2254

You should authenticate your client before making the request. From your call you are providing a ajax POST request hit.

Provide a header in your RESTClient: X-CSRFToken.

For more details view this

Upvotes: 1

Related Questions