Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling Django CSRF for views that do not always have a response

I have a Django view that receives POSTs which do not need to have the CSRF token. Therefore I used the @csrf_exempt decorator on the view. The problem is that sometimes I do not issue a response from the view (it's a Twitter bot, it receives an HTTP POST for every tweet and I do not want to respond to every tweet). When I don't issue a response I get the following error:

Traceback (most recent call last):

 File "/home/adam/webapps/newman/lib/python2.5/django/core/handlers/base.py", line 100, in get_response
   response = callback(request, *callback_args, **callback_kwargs)

 File "/home/adam/webapps/newman/lib/python2.5/django/views/decorators/csrf.py", line 24, in wrapped_view
   resp.csrf_exempt = True

AttributeError: 'NoneType' object has no attribute 'csrf_exempt'

resp (which I assume is the response) is None because the view was exited with just return. How can I avoid this error and still not require CSRF tokens in the POST.

Thanks!

like image 841
Adam Avatar asked Jul 17 '10 00:07

Adam


1 Answers

I know you already got your answer, and indeed Ned's right; but in addition to that: not only Django really expects views to return a response, your client also! It's an HTTP error and likely a resource waste not to return something (and thus close the connection straight away)!

I would think that a 204 No Content or 304 Not modified (see: HTTP Status Codes) are the appropriate http codes to use in this situation; in django:

return HttpResponse(status=204)

or

from django.http import HttpResponseNotModified
return HttpResponseNotModified()
like image 196
Stefano Avatar answered Sep 25 '22 19:09

Stefano