错误:“CSRF验证失败。请求中止。“当使用jquery json和Django时

时间:2021-12-01 02:53:21

I want to retrieve json data and put it to database. I'm using django

我想检索json数据并将其放入数据库。我正在使用django

When i post json i receive this error: Forbidden (403) CSRF verification failed. Request aborted.

当我发布json时,我收到此错误:禁止(403)CSRF验证失败。请求中止。

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))

2 个解决方案

#1


1  

This error is raised, when you try to post data outer than a django form.

当您尝试在django表单之外发布数据时,会引发此错误。

The simple, but UNSAFE method is to add @csrf_exempt before your views, like:

简单但是UNSAFE方法是在您的视图之前添加@csrf_exempt,例如:

@csrf_exempt
def my_view(request):
    pass

The not that simple method is written here: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

这里写的不是那么简单的方法:https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

#2


1  

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


1  

This error is raised, when you try to post data outer than a django form.

当您尝试在django表单之外发布数据时,会引发此错误。

The simple, but UNSAFE method is to add @csrf_exempt before your views, like:

简单但是UNSAFE方法是在您的视图之前添加@csrf_exempt,例如:

@csrf_exempt
def my_view(request):
    pass

The not that simple method is written here: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

这里写的不是那么简单的方法:https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

#2


1  

This is the solution i found:

这是我发现的解决方案:

from django.views.decorators.csrf import csrf_exempt

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