R – Prepend BOM to XML response from Django

byte-order-markdjangoxml

I use Django's render_to_response to return an XML document. This particular XML document is intended for a flash-based charting library. The library requires that the XML document start with a BOM (byte order marker). How can I make Django prepent the BOM to the response?

It works to insert the BOM into the template, but it's inconvenient because Emacs removes it every time I edit the file.

I have tried to rewrite render_to_response as follows, but it fails because the BOM is being UTF-8 encoded:

def render_to_response(*args, **kwargs):
    bom = kwargs.pop('bom', False)
    httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)}
    s = django.template.loader.render_to_string(*args, **kwargs)
    if bom:
        s = u'\xef\xbb\xbf' + s
    return HttpResponse(s, **httpresponse_kwargs)

Best Answer

You're not really talking about a BOM (Byte Order Mark), since UTF-8 doesn't have a BOM. From your example code, the library expects the text to have 3 garbage bytes prepended for some inexplicable reason.

Your code is almost correct, but you must prepend the bytes as bytes, not characters. Try this:

def render_to_response(*args, **kwargs):
    bom = kwargs.pop('bom', False)
    httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)}
    s = django.template.loader.render_to_string(*args, **kwargs)
    if bom:
        s = '\xef\xbb\xbf' + s.encode("utf-8")
    return HttpResponse(s, **httpresponse_kwargs)