X-UA-Compatible Django Middleware

by

When Microsoft’s Internet Explorer 8 was released this past March, it included a fairly decent standards-compliant rendering engine. While a step forward for the web, a compliant rendering engine breaks many web sites that were developed for previous versions of IE. Internal corporate and government networks are notorious for sites that were built for IE 6 or 7 and often took advantage of bugs in the rendering engines. To prevent these sites, and others across the web, from breaking, IE 8 will sometimes use one of the older rendering engines.

There are various conditions that are used to select the engine that will be used to render the page. The good news is that you, as a web developer, can instruct IE 8 to use a specific engine to render your site. This can be done by using the X-UA-Compatible HTTP header or HTML meta tag.

Sunlight Labs has written middleware and a decorator for Django that will take care of sending the appropriate HTTP header. Include the following in settings.py to enable the middleware:

MIDDLEWARE_CLASSES = (
    ...
    'compatibility.XUACompatibleMiddleware',
)

The middleware will send a default X-UA-Compatible header of IE=edge for any HTML or XHTML response. The default value can be overridden by including the following in settings.py:

X_UA_COMPATIBLE = 'IE=EmulateIE7'

In some cases it may be necessary to set the value of the X-UA-Compatible header on a per-view basis. This can be accomplished using the provided decorator:

from compatibility import xuacompatible

@xuacompatible('IE=EmulateIE7')
def index(request):
    ...

X-UA-Compatible middleware and decorator on GitHub