Gilang Chandrasa Thoughts, stories, and ideas

Generate QR Code In Django Model

What is QR Code?

Taken from wikipedia definition of qrcode

QR code (abbreviated from Quick Response Code) is the trademark for a type of matrix barcode (or two-dimensional barcode) first designed for the automotive industry in Japan. A barcode is a machine-readable optical label that contains information about the item to which it is attached. A QR code uses four standardized encoding modes (numeric, alphanumeric, byte/binary, and kanji) to efficiently store data;

Or from qrcode project on github.

A Quick Response code is a two-dimensional pictographic code used for its fast readability and comparatively large storage capacity. The code consists of black modules arranged in a square pattern on a white background. The information encoded can be made up of any kind of data (e.g., binary, alphanumeric, or Kanji symbols)

Installation and implementation

First, let’s install qrcode for generating QR code. Visit qrcode github page for more details.

$ pip install qrcode==5.1

The following model have a method called generate_qrcode that will generate qr code (hello! so obvious right?).

import qrcode
import StringIO

from django.db import models
from django.core.urlresolvers import reverse
from django.core.files.uploadedfile import InMemoryUploadedFile


class Event(models.Model):
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True)

    qrcode = models.ImageField(upload_to='qrcode', blank=True, null=True)

    def get_absolute_url(self):
        return reverse('events.views.details', args=[str(self.id)])

    def generate_qrcode(self):
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=6,
            border=0,
        )
        qr.add_data(self.get_absolute_url())
        qr.make(fit=True)

        img = qr.make_image()

        buffer = StringIO.StringIO()
        img.save(buffer)
        filename = 'events-%s.png' % (self.id)
        filebuffer = InMemoryUploadedFile(
            buffer, None, filename, 'image/png', buffer.len, None)
        self.qrcode.save(filename, filebuffer)

so all you need to do on your template is showing that qrcode.

<img src="{{ event.qrcode.url }}" alt="Event QR code" />