How to display a custom error page for HTTP status 405 (method not allowed) in Django

written by Herman Schaaf on Jan. 10, 2011
Find me on Twitter, Google+ or LinkedIn

I recently realized that, despite Django having the built-in (and very useful) @require_POST decorator, there is actually no easy way to display a nice error page if the user accidentally stumbles onto a page using a GET request (or vice-versa for the @require_GET decorator). In fact, Django doesn't even show the usual error page in debug mode. But there is a nice, Django-oriented way to do it: Middleware.

Loosely based on the tutorial given here for 403 pages, here's what you have to do:

Create the Middleware

  1. Create a directory at the root of your project called “middleware”
  2. Add a file named “__init__.py” to this directory
  3. Create a file named “http.py” in this directory with the following contents:
    from django.http import HttpResponseNotAllowed from django.template
    import RequestContext from django.template import loader class HttpResponseNotAllowedMiddleware(object):
        def process_response(self, request, response):
            if isinstance(response, HttpResponseNotAllowed):
                context = RequestContext(request)
                response.content = loader.render_to_string("405.html", context_instance=context)
            return response  
  4. Add ” ‘myproject.middleware.http.HttpResponseNotAllowedMiddleware’, ” to your MIDDLEWARE_CLASSES in settings.py

Create the custom template

Add a custom "405.html" page to your templates folder, containing the error message you would like to display. You could also adapt the code example above to check for the existence of this template, catch a TemplateDoesNotExist exception otherwise, and then render a shorter message straight in the code. 

That's it! Now Django will display your custom 405 error page every time the user goes onto a page that expects another method.



If you found this post interesting, you might also like our blog post, Guest post series: Behind the Screens at progr.es