@csrf_exempt在Django 1.4中停止工作 [英] @csrf_exempt stopped working in Django 1.4
本文介绍了@csrf_exempt在Django 1.4中停止工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码,在Django 1.2.5中可以正常工作:
I have the following code, that was working fine in Django 1.2.5:
from django.views.decorators.csrf import csrf_exempt
class ApiView(object):
def __call__(self, request, *args, **kwargs):
method = request.method.upper()
return getattr(self, method)(request, *args, **kwargs)
@csrf_exempt
class MyView(ApiView):
def POST(self):
# (...)
return HttpResponse(json.dumps(True), mimetype="text/javascript")
但是当我升级到Django 1.4时,我开始获得403被禁止的CSRF验证失败消息。
But when I upgraded to Django 1.4, I started to get a 403 forbidden, with a "CSRF verification failed" message.
为什么@csrf_exempt装饰器不起作用?
Why is that @csrf_exempt decorator not working?
URL定义是:
from django.conf.urls.defaults import *
from django.views.decorators.csrf import csrf_exempt
import views
urlpatterns = patterns('',
url(r'^myview/(?P<parameter_name>[A-Za-z0-9-_]+)/$',
views.MyView(),
name="myproject-myapp-myview",
),
)
推荐答案
根据 django docs :
为了装饰基于类视图的每个实例,您需要为类定义本身装饰
。为此,您可以将装饰器应用于类的
dispatch()方法。
To decorate every instance of a class-based view, you need to decorate the class definition itself. To do this you apply the decorator to the dispatch() method of the class.
所以你需要请执行以下操作:
So you'd need to do something like:
class MyView(ApiView):
def POST(self):
# (...)
return HttpResponse(json.dumps(True), mimetype="text/javascript")
@csrf_exempt
def dispatch(self, *args, **kwargs):
return super(MyView, self).dispatch(*args, **kwargs)
这篇关于@csrf_exempt在Django 1.4中停止工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文