Search code examples
pythondjangopython-webbrowser

In Python, how to open a string representing HTML in the browser?


I'd like to view a Django template in the browser. This particular template is called in render_to_string, but is not connected to a view, so I can't just runserver and navigate to the URL at my localhost.

My idea was to simply call render_to_string in the Django shell and somehow pass the resulting string to a web browser such as Chrome to view it. However, as far as I can tell the webbrowser module only accepts url arguments and can't be used to render strings representing HTML.

Any idea how I could achieve this?


Solution

  • Use Data URL:

    import base64
    
    html = b"..."
    
    url = "text/html;base64," + base64.b64encode(html)
    webbrowser.open(url)