【问题标题】:error: “CSRF verification failed. Request aborted.” when using jquery json with Django错误:“CSRF 验证失败。请求中止。”将 jquery json 与 Django 一起使用时
【发布时间】:2014-10-20 21:19:45
【问题描述】:

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

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

代码

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

【问题讨论】:

    标签: python json django


    【解决方案1】:

    这是我找到的解决方案:

    from django.views.decorators.csrf import csrf_exempt
    
    @csrf_exempt
    def my_view(request):
        return HttpResponse('Hello world')
    

    【讨论】:

      【解决方案2】:

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

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

      @csrf_exempt
      def my_view(request):
          pass
      

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

      【讨论】:

        猜你喜欢
        • 2021-11-12
        • 2012-03-12
        • 2014-11-03
        • 2012-12-07
        • 2015-03-08
        • 1970-01-01
        • 2015-02-28
        • 2014-02-03
        相关资源
        最近更新 更多