Jeffrey Gelens

Django XHTML-Mortifier

Last week I decided to set the content-type of my xhtml-pages to application/xhtml+xml. This of course caused some problems for IE as it doesn't accept this content-type. I found some Django middleware snippet which can do this convertion, however it was doing too much for me. So I rewrote it to fulfil my needs.

Also my uber Django-blog supports reStructuredText markup now (in addition to Textile) and along with that I implemented syntax highlighting using Pygments.

Anyway, here's the middleware source (using the cool Pygments highlighter):

import re

CONTENT_TYPE_RE = re.compile(r'="application\/xhtml\+xml')
HTML_RE = re.compile(r'html', re.I)

class XhtmlMortifierMiddleware(object):
    """
    This middleware converts responses set with the application/xhtml+xml
    content-type to text/html if the user-agent does not accept XHTML responses.
    Other kind of responses are being ignored.

    Make sure the XhtmlMortifierMiddleware appears after the GZipMiddleware in
    the MIDDLEWARE_CLASSES list in settings.py.
    """

    def _accepts_xhtml(self, request):
        if "/xhtml+xml" in request.META.get("HTTP_ACCEPT", "").lower():
            return True
        else:
            return False

    def process_response(self, request, response):
        if not HTML_RE.search(response["Content-Type"]):
            return response
        if self._accepts_xhtml(request) and not \
                response["Content-Type"].split(";")[0] == "text/html":
            response["Content-Type"] = "application/xhtml+xml; charset=utf-8"
        else:
            response["Content-Type"] = "text/html; charset=utf-8"
            response.content = CONTENT_TYPE_RE.sub('="text/html', \
                response.content, 1)
            response['Content-Length'] = str(int(response['Content-Length']) - 12)
        return response

I listed it on Djangosnippets

Ugh Seriously, why?? Are you using MathML or something? read http://www.tangerinesmash.com...

Jeffrey Gelens Everyone's own taste?