我有以下代码,在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验证失败”消息。
为什么@csrf_exempt装饰器无效?
网址定义是:
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",
),
)
答案 0 :(得分:22)
根据django docs:
要装饰基于类的视图的每个实例,您需要进行装饰 类定义本身。要执行此操作,请将装饰器应用于 类的dispatch()方法。
所以你需要做类似的事情:
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)
答案 1 :(得分:12)
只需在csrf_exempt
中使用urls.py
即可。即:
..other imports...
from django.views.decorators.csrf import csrf_exempt
from myapp.views import MyView
urlpatterns = patterns('',
url(r'^myview/(?P<parameter_name>[A-Za-z0-9-_]+)/$',
csrf_exempt(MyView.as_view()), # use csrf_exempt here
name="myproject-myapp-myview",
),
)
答案 2 :(得分:3)
csrf_exempt必须装饰一个函数。在您的网址中,您可以修饰该功能docs can be found here。
(r'^vote/', permission_required('polls.can_vote')(VoteView.as_view())),