あるフリーランスエンジニアの色んなメモ!! ITスキル・ライフハックとか

Django:Class-based generic viewのCSRF checkを無効化する

実装例

関数に直接csrf_exemptを付ける

from django.views import View
from django.views.decorators.csrf import csrf_exempt


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

関数にmethod_decoratorを付ける

from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator


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

クラスにmethod_decoratorを付ける

from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator


@method_decorator(csrf_exempt, name='dispatch')
class SampleView(View):
    ...
comments powered by Disqus