Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 201
Kurt Peek Avatar asked Mar 11 '26 06:03

Kurt Peek


1 Answers

Use Data URL:

import base64

html = b"..."

url = "text/html;base64," + base64.b64encode(html)
webbrowser.open(url)
like image 54
Marat Avatar answered Mar 13 '26 19:03

Marat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!