Login

QRCode template tag

Author:
bradbeattie
Posted:
November 22, 2012
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)

I had a hell of a time getting most QR code stuffs out there working with Django. Many projects, but problems here and problems there. The only additional code you'll need for this is to "pip install qrcode". After that, you're free to <img src="{% qrcode_datauri "http://localhost:8000/" %}" />.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from base64 import b64encode
from django.template.base import Library
import cStringIO
import qrcode


register = Library()


@register.simple_tag
def qrcode_datauri(data, pixel_size=5, border_pixels=1, error_correction="H"):
    qrcode_object = qrcode.QRCode(
        error_correction=getattr(
            qrcode.constants,
            "ERROR_CORRECT_%s" % error_correction,
            "H" 
        ),  
        box_size=max(1, min(100, pixel_size)),
        border=max(1, min(100, border_pixels)),
    )   
    qrcode_object.add_data(data)
    qrcode_object.make(fit=True)
    qrcode_image = qrcode_object.make_image()
    byte_stream = cStringIO.StringIO()
    qrcode_image.save(byte_stream)
    datauri = "data:image/png;base64,%s" % b64encode(byte_stream.getvalue())
    byte_stream.close()
    return datauri

More like this

  1. find even number by Rajeev529 1 month, 1 week ago
  2. Form field with fixed value by roam 1 month, 4 weeks ago
  3. New Snippet! by Antoliny0919 2 months ago
  4. Add Toggle Switch Widget to Django Forms by OgliariNatan 4 months, 3 weeks ago
  5. get_object_or_none by azwdevops 8 months, 2 weeks ago

Comments

jeanpierre1995 (on December 6, 2017):

Buenísimo, me funcionó a buena hora !!!

Como puedo mandar ese

<img src="{% qrcode_datauri codigo %}"/>

Dónde "codigo" es mi objeto y quiero mandar al gmail esta img cómo lo haría ? .. Solo me falta enviar esa imagen de qrcode ... Necesito su ayuda

Muchas gracias de antemano !!!

#

Please login first before commenting.