Search code examples
pythonhtmlflaskrenderqr-code

How to embed a qr code png image in html template page?


I am generating the qr image using the below code.

url="https://www.google.com"
img = qrcode.make(url)
img.save("displayQrInvite.png")
return render_template('invite.html')

Below is the html template file.

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My App</title>
</head>
<body>
    
    <h1>Scan below qr code image</h1>
    <img src="/displayQrInvite.png"/>
</body>
</html>

Somehow the image is not visible on any of the browsers chrome,edge.c

enter image description here


Solution

  • It appears that the QR code is being generated at a different path. To resolve this and ensure a consistent display of generated QR codes, it is best to set the output to a static files directory. In addition to the documentation, this question provides some good insight on this.

    In your case, what the code would look like is:

    # main.py
    @app.route("/qr-code")
    def display_qr_code():
        url="https://www.google.com"
        img = qrcode.make(url)
        img.save("static/images/displayQrInvite.png")
    
        return render_template("qr_code.html")
    
    <!-- qr_code.html -->
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>My App</title>
        </head>
        <body>
            <h1>Scan below qr code image</h1>
            <img src="{{ url_for('static', filename='images/displayQrInvite.png') }}"/>
        </body>
    </html>
    

    The directory structure would look like this:

    your_project
    |- static
    |----- images
    |- templates
    |----- qr_code.html
    |- main.py