class ChromeLoginView(View):
def get(self, request):
return JsonResponse({'status': request.user.is_authenticated()})
@method_decorator(csrf_exempt)
def post(self, request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return JsonResponse({'status': True})
return JsonResponse({'status': False})
投稿が csrf によって停止されることを期待していますが、403 エラーが返されます。
しかし、そのデコレータを削除してURLConfでこれを行うと
url(r'^chrome_login/', csrf_exempt(ChromeLoginView.as_view()), name='chrome_login'),
それが動作します。
ここで何が起こったのでしょうか? 動作するはずではなかったのでしょうか。おそらく、それが method_decorator の機能だと思います。私は python3.4 と django1.7.1 を使用しています。
どのようなアドバイスでも大歓迎です。
ベストアンサー1
@knbk が言ったように、これはdispatch()
装飾する必要があるメソッドです。
Django 1.9以降、method_decorator
クラスに直接使用することができます:
from django.utils.decorators import method_decorator
@method_decorator(csrf_exempt, name='dispatch')
class ChromeLoginView(View):
def get(self, request):
return JsonResponse({'status': request.user.is_authenticated()})
def post(self, request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return JsonResponse({'status': True})
return JsonResponse({'status': False})
これにより、dispatch()
メソッドを装飾するためだけにオーバーライドすることが回避されます。