15

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!

efotinis
  • 14,565
  • 6
  • 31
  • 36
Adam
  • 43,763
  • 16
  • 104
  • 144

2 Answers2

9

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()
Stefano
  • 18,083
  • 13
  • 64
  • 79
7

Django really expects view functions to return responses. Maybe you could return an empty response instead of None? Or return an HTTP error code?

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662