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

Pyt*_*ast 1 django django-csrf django-class-based-views

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

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})
Run Code Online (Sandbox Code Playgroud)

它说,每当我在这个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/"
Run Code Online (Sandbox Code Playgroud)

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

iam*_*ush 5

这是因为class_based意见,你需要decoratedispatch 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():
  ....
Run Code Online (Sandbox Code Playgroud)


Bog*_*suc 5

您可以简单地从 CBV 创建视图,并用装饰器包装它,如下所示:

user_view = csrf_exempt(UserCreate.as_view())

完整示例:

视图.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())
Run Code Online (Sandbox Code Playgroud)

urls.py

from myapp.views import user_create

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