1
votes

I'm using 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})

Whenever I post data on this URL, it says 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/"

I've had this problem while getting data from the form in function views. There I used to add @csrf_exempt on my view and it would work. When I added @csrf_exempt to my post method, it does not work. How can I post the data?

3
For more information on class decoration, here is the link to the related django docs: docs.djangoproject.com/en/1.11/topics/class-based-views/intro/…Pitt

3 Answers

6
votes

This is because is class_based views you need to decorate the dispatch method for csrf_exempt to work

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

  def post():
  ....
4
votes

You can simply create the view from the CBV, and wrap it with the decorator like this:

user_view = csrf_exempt(UserCreate.as_view())

Complete example:

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
votes

@csrf_exempt is a decorator for functions, not Class Based Views. In order to get CSRF Exempt on a CBV install django-braces and import CsrfExemptMixin as follows:

from braces.views import CsrfExemptMixin

and implement it this way:

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