10

I'd like to return 410 errors at for some of my Django pages instead of returning 404s. Basically, instead of calling raise Http404('some error message'), I would like to instead call raise Http410('some error message') shortcut.

I am confused because in django.http, the function Http404 is simply:

class Http404(Exception):
    pass

So if I do the same thing and create my Http410 function, I would assume it would look like:

class Http410(Exception):
    pass

However, doing this returns the exception but serves up a 500 error page. How do I recreate the magic of the Http404 exception? I should note, I need to raise the exception from my models (not views) so I can't just return an HttpResponseGone.

Thanks in advance!

Update: I am fully aware of HttpResponseGone and mentioned this in my original question. I already know how to return this in my views. My question is: How do you raise an Http 410 exception similarly to how you raise an Http 404 exception? I want to be able to raise this exception anywhere, not just in my views. Thanks!

James A Mohler
  • 11,060
  • 15
  • 46
  • 72
Spike
  • 5,040
  • 5
  • 32
  • 47

3 Answers3

24
from django.http import HttpResponse
return HttpResponse(status=410)
Spike Gronim
  • 6,154
  • 22
  • 21
16

Django does not include a mechanism for this because gone should be normal workflow, not an error condition, but if you want to not treat it as a return response, and as an exception, just implement a middleware.

class MyGoneMiddleware(object):
    def process_exception(self, request, exception):
        if isinstance(exception, Http410):
            return HttpResponseGone("Gone!")
        return None
Mike Axiak
  • 11,827
  • 2
  • 33
  • 49
  • @Spike Any reason why you can't just return a `HttpResponseGone` object instead of raising an exception and having the middleware inject the object, instead? – Santa Nov 18 '10 at 08:08
  • I decided to just return a HttpResponseGone object since that seems to be the normal way to do things. I am keeping your answer marked as answered, though, because you answered the exact question I originally asked. – Spike Nov 18 '10 at 14:06
  • @Santa It would be nice to raise instead of return because sometimes you need to do it from within a deeply nested function call, far away from your view function. – Jonathan Hartley Sep 25 '15 at 12:47
11

Return a HttpResponseGone, a subclass of HttpResponse, in your view handler.

Santa
  • 11,381
  • 8
  • 51
  • 64