Display SVG image from qrcode in Django

Viewed 1556

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
2 Answers

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 }}

To solve this I transformed the <qrcode.image.svg.SvgImage> into a base64 string, this can then be used as an img src="{{variable}}" in HTML.

import io
import base64

from qrcode import make as qr_code_make
from qrcode.image.svg import SvgPathFillImage

def get_qr_image_for_user(qr_url: str) -> str:
    svg_image_obj = qr_code_make(qr_url, image_factory=SvgPathFillImage)
    image = io.BytesIO()
    svg_image_obj.save(stream=image)
    base64_image = base64.b64encode(image.getvalue()).decode()
    return 'data:image/svg+xml;utf8;base64,' + base64_image

If this is not a good solution I would love some feedback. Cheers

Related