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"]) or \ response.has_header('Location'): 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