Django CSRF Verifcation失败 - 基于类的视图

时间:2015-10-10 08:45:53

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

我使用的是基于类的视图。

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

每当我在此网址上发布数据时,都会显示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方法时,它不起作用。我该如何发布数据?

3 个答案:

答案 0 :(得分:5)

这是因为基于class_based的视图需要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():
  ....

答案 1 :(得分:3)

@csrf_exempt是函数的装饰器,而不是基于类的视图。为了在CBV安装django-braces上获得CSRF豁免并导入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})

答案 2 :(得分:3)

你可以简单地从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'),
    ...
]