Q:

Display SVG image from qrcode in Django

As per the qrcode docs, I generate an SVG QR code:
import qrcode
import qrcode.image.svg
def get_qrcode_svg( uri ):
    img = qrcode.make( uri, image_factory = qrcode.image.svg.SvgImage)
    return img

And that's all fine. I get a <qrcode.image.svg.SvgImage object at 0x7f94d84aada0> object.
I'd like to display this now in Django html. I pass this object as context (as qrcode_svg) and try to display with <img src="{{qrcode_svg}}"/> but don't get really anywhere with this. The error shows it's trying to get the img url, but isn't there a way I can do this without saving the img etc.? Terminal output:
>>> UNKNOWN ?????? 2020-06-16 07:38:28.295038 10.0.2.2 GET 
/user/<qrcode.image.svg.SvgImage object at 0x7f94d84aada0>
Not Found: /user/<qrcode.image.svg.SvgImage object at 0x7f94d84aada0>
"GET /user/%3Cqrcode.image.svg.SvgImage%20object%20at%200x7f94d84aada0%3E HTTP/1.1" 404 32447

A:

You can write it to the response stream:
import qrcode
from qrcode.image.svg import SvgImage
from django.http import HttpResponse
from bytesIO import bytesIO

def get_qrcode_svg(uri):
    stream = bytesIO()
    img = qrcode.make( uri, image_factory=SvgImage)
    img.save(stream)
    return stream.getvalue().decode()
This will pass the svg source, not a URI with the source code. In the template, you thus render this with:
{{ qrcode_svg|safe }}

