【问题标题】:Django CSRF Verifcation failed - Class based viewsDjango CSRF 验证失败 - 基于类的视图
【发布时间】:2015-10-10 08:45:53
【问题描述】:

我正在使用基于类的视图。

class UserCreate(View):
    def post(self, request):
        data = request.data.get
        social_id = data('social_id')
        social_source = data('social_source')
        user = User(social_id=social_id, social_source=social_source, access_token=access_token)
        user.save()
        return JsonResponse({'response':200})

每当我在此 URL 上发布数据时,它都会显示 CSRF token missing or incorrect.

curl -X POST --header "Content-Type: application/json" --header "Accept: application/json" -d "{
  \"social_id\": \"string\",
  \"social_source\": \"FB/Gmail\",
  \"access_token\": \"string\"
}" "http://127.0.0.1:8000/users/"

我在函数视图中从表单获取数据时遇到了这个问题。我曾经在我的视图中添加@csrf_exempt,它会起作用。当我将@csrf_exempt 添加到我的post 方法时,它不起作用。如何发布数据?

【问题讨论】:

标签: django django-class-based-views django-csrf


【解决方案1】:

这是因为你需要 decorate dispatch method 才能使 csrf_exempt 工作

class UserCreate(View):
  @method_decorator(csrf_exempt)
  def dispatch(self, request, *args, **kwargs):
    return super(UserCreate, self).dispatch(request, *args, **kwargs)

  def post():
  ....

【讨论】:

  • 谢谢。这对我很有帮助。
【解决方案2】:

您可以简单地从 CBV 创建视图,然后用装饰器将其包装起来,如下所示:

user_view = csrf_exempt(UserCreate.as_view())

完整示例:

views.py

class UserCreate(View):
    def post(self, request):
        data = request.data.get
        social_id = data('social_id')
        social_source = data('social_source')
        user = User(social_id=social_id, social_source=social_source, access_token=access_token)
        user.save()
        return JsonResponse({'response':200})

user_create = csrf_exempt(UserCreate.as_view())

urls.py

from myapp.views import user_create

urlpatternts = [
    ...
    url(r'^pattern-here/$', user_create, name='user-create'),
    ...
]

【讨论】:

  • 我添加了完整的例子。
【解决方案3】:

@csrf_exempt 是函数的装饰器,而不是基于类的视图。为了在 CBV 上获得 CSRF Exempt,请安装 django-braces 并导入 CsrfExemptMixin,如下所示:

from braces.views import CsrfExemptMixin

并以这种方式实现它:

class UserCreate(CsrfExemptMixin, View):
    def post(self, request):
        data = request.data.get
        social_id = data('social_id')
        social_source = data('social_source')
        user = User(social_id=social_id, social_source=social_source, access_token=access_token)
        user.save()
        return JsonResponse({'response':200})

【讨论】:

    猜你喜欢
    • 2012-09-08
    • 2015-06-02
    • 1970-01-01
    • 2017-03-29
    • 2011-06-14
    • 2020-03-24
    相关资源
    最近更新 更多