How to Generate a QR Code in Django

If you are one of them who is searching for How to generate a QR Code in Django then, you landed on the correct webpage. In this post, We will see how we can generate QR code using Django Python Framework.

What are QR codes?

QR code, or quick response code, trademark for a king of two-dimensional barcodes. 2-dimensional barcodes are almost like one-dimensional barcodes but can store more information per unit area.

Below I have explained how one can generate a QR code in Django. So, Stay Tuned with this webpage.

This is a small project that will generate a QR code for any text and pass it to the HTML template as an SVG code.

How to Generate a QR Code in Django

SVG is a very convenient medium for URLs or other text. This small demo demonstrates a few things:

Why use SVG for QR Codes?

SVG is a highly convenient medium for web applications because:

  • It is resolution-independent (it won’t look blurry when zoomed).
  • It can be passed directly to HTML templates as a string.
  • It eliminates the need for managing temporary image files on your server.

The Tutorial

  1. Environment Setup
  2. Project Configuration
  3. Building the Logic (views.py)
  4. Creating the Frontend (index.html)

Environment Setup
We want our code to be shown at a root URL, so we need to add the following URL in urls.py:

from django.contrib import admin
from django.urls import path
from your_app import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index)
]

Project Configuration

Create your Django project and an app. You won’t need a database model for this specific task as we are processing data in real-time.

In your urls.py, set up the root path to point to your generator view:

from django.contrib import admin
from django.urls import path
from your_app import views

urlpatterns = [
path(‘admin/’, admin.site.urls),
path(”, views.index)
]

Building the Logic (views.py)
Go to your_app/views.py file and write this:

from django.shortcuts import render
import qrcode
import qrcode.image.svg
from io import BytesIO


def index(request):
    context = {}
    if request.method == "POST":
        factory = qrcode.image.svg.SvgImage
        img = qrcode.make(request.POST.get("qr_text",""), image_factory=factory, box_size=20)
        stream = BytesIO()
        img.save(stream)
        context["svg"] = stream.getvalue().decode()

    return render(request, "index.html", context=context)

Here we check if there’s something posted within the request, i.e., the user has entered a text and pressed “submit”.

If true, we generate the corresponding QR code and reserve it to the context. You may change the dimensions of your QR code with the “box_size” parameter.

The BytesIO helps us avoid writing to a file and obtain the content immediately so it are often passed to the HTML renderer that takes index.html as a template. Yes, we’d like this index.html .

Go to your templates folder (do not forget to specify this folder in settings.py, by the way) and make a file called index.html:

Creating the Frontend (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>QR Code Generator</title>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
        rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6"
        crossorigin="anonymous">
</head>
<body>
  <div class="container shadow"
       style="width: 800px; margin-top: 5em; padding: 2em">
    <form method="post">
      {% csrf_token %}
      <h3>Enter any text to generate a QR code</h3>
      <div class="input-group mb-3">
        <span class="input-group-text"
              id="inputGroup-sizing-default">QR Code Text:</span>
        <input type="text"
               class="form-control"
               aria-describedby="inputGroup-sizing-default"
               name="qr_text"
               autofocus>
      </div>
      <div class="input-group mb-3">
        <input type="submit" style="max-width: 200px; margin: auto" class="form-control">
      </div>
    </form>
      <div class="input-group mb-3">
        <div style="margin: auto">
          {{ svg|safe }}
        </div>
      </div>
  </div></body>
</html>

Key Takeaways

  1. Dynamic Generation: By using BytesIO, you avoid cluttering your MEDIA_ROOT with temporary QR code files.
  2. SVG Factory: The qrcode.image.svg.SvgImage factory is what allows the library to output XML instead of a PNG/JPEG.
  3. Template Safety: Always use {{ variable|safe }} when injecting raw SVG or HTML from your view into a template.

It’s pretty simple: we load bootstrap for styles (yes, i do know that this is often an overkill), display an input form, and display the SVG content if it had been passed within the context.

Here, it’s important to flee SVG with “safe” parameter: {{ svg|safe }} . In this manner we tell the renderer to not be afraid and insert the tag as is.

I hope this Help you all.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *