Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@csrf_exempt stopped working in Django 1.4

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")

But when I upgraded to Django 1.4, I started to get a 403 forbidden, with a "CSRF verification failed" message.

Why is that @csrf_exempt decorator not working?

URL definition is:

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",
       ),
)
like image 490
lfagundes Avatar asked Apr 20 '12 19:04

lfagundes


1 Answers

According to the django docs:

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)
like image 64
dgel Avatar answered Oct 06 '22 14:10

dgel