16

我有以下代码,在 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",
       ),
)
4

3 回答 3

22

根据django 文档

要装饰基于类的视图的每个实例,您需要装饰类定义本身。为此,您将装饰器应用于类的 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)
于 2012-04-20T19:39:29.030 回答
12

只需csrf_exempturls.py. IE::

网址.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",
       ),
)
于 2014-04-13T18:33:12.807 回答
3

csrf_exempt 必须装饰一个函数。在您的网址中,您可以装饰该功能,可以在此处找到文档

(r'^vote/', permission_required('polls.can_vote')(VoteView.as_view())),
于 2012-04-20T20:12:00.507 回答