How to Generate QR Code Using Django

In this article, we will learn how generate a QR code using Django python. Here we generate QR code images from any text.

First, we need to install the following packages

Step-1

  1. pip install qrcode

Step-2

  1. create django project
  2. create django app

then include the app in the settings.py file

Create views.py


from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect 
import io   
import qrcode.image.svg 
import qrcode
  
def qr_code(request): 
    context ={}
    if request.method == "POST":
        factory = qrcode.image.svg.SvgImage
        qr_image = qrcode.make(request.POST.get("https://labpys.com",""),image_factory=factory, box_size=20)    
        bufstore = io.BytesIO()
        qr_image.save(bufstore)    
        context["svg"] = bufstore.getvalue().decode()   
    return render(request,'qrcode.html',context=context)

Now to set url in urls.py

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include("qr_code.urls")),
]
 




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

urlpatterns = [
   path("",views.qr_code,name="qrcode"),
]

then Create Template folder in that create HTML file qrcode.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>QR Code Generator</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">  
 
</head>
<body>
  <div class="row col-sm-6 shadow">
    <form method="post">
      {% csrf_token %}
      <h3>generate a QR code(Enter Any text)</h3>
      <div class="row-group">         
        <input type="text"  class="form-control" name="qr_text" autofocus>
      
      <br/>
      <div class="row-group">
        <input type="submit" style="max-width: 200px; margin: auto" class="form-control">
      </div>
      <br/>
    </div>
    </form>
      <div class="row-group">
        <div style="margin: auto">
          {{ svg|safe }}
        </div>
      </div>
  </div>
</body>
</html>

Thank you for reading.

4.7 3 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments