Error: "CSRF check failed. Request aborted." when using jquery json with Django

I want to get json data and put it in a database. I am using django

When I submit json, I get this error: Forbidden (403) Failed to perform CSRF validation. The request was aborted.

code

def receiver(request):
    try:
        json_data = request_to_json(request)  

        # Retrieving json data
        x = json_data['x']
        y = json_data['y']
        z = json_data['z']
        # put it in database

        db = db_connection().db;
        db_manager= db_management(db);
        db_manager.insert_point(x,y,z,x);
        db.close() 

        # A variable to return to the app
        response = 'OK'

    except:
        response = 'Error'

    return HttpResponse(simplejson.dumps(response))

      

+3


source to share


2 answers


This error occurs when you are trying to post data outward than django form.

A simple but UNSAFE method is to add @csrf_exempt

before your views, for example:



@csrf_exempt
def my_view(request):
    pass

      

Wrong method is written here: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

+1


source


This is the solution I found:



from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def my_view(request):
    return HttpResponse('Hello world')

      

+1


source







All Articles