Version 2 (modified by nesh <nesh [at] studioquattro [dot] co [dot] yu>, 11 years ago) (diff)

I can't post comment to his blog, so I write comment here

Contributed Middleware

XHTMLAsHTMLMiddleware by Sune Kirkeby

Sends application/xhtml+xml header to browsers that understand it.

I'm tried to add comment to his blog and that fails for some reason, so I'm adding that comment here:

Well you reversed parameters in replace ;), also I think that using re for checking Accept header is a bit of a overkill, here is my solution:

class XHTMLAsHTMLMiddleware:
    """I change content-type application/xhtml+xml into text/html, if the
    browser does not support the XHTML content-type."""

    def process_response(self, request, response):
        accept = request.META.get('HTTP_ACCEPT', '')
        user_agent = request.META.get('HTTP_USER_AGENT', '')
        if ('application/xhtml+xml' in accept) or ('W3C_Validator' in user_agent):
            ct = response['Content-Type']
            ct = ct.replace('text/html', 'application/xhtml+xml')
            response['Content-Type'] = ct
        if ';' not in response['Content-Type']:
            # add default encoding
            ct = response['Content-Type']
                from django.conf.settings import DEFAULT_ENCODING
            except ImportError:
                DEFAULT_ENCODING = 'utf-8'
            ct = ct + '; charset=' + DEFAULT_ENCODING
            response['Content-Type'] = ct
        return response
    # process_response
# XHTMLAsHTMLMiddleware

I'm also added charset part to Content-Type.

Attachments (5)

Download all attachments as: .zip

Back to Top