QR code generating website in Django

PythonServer Side ProgrammingProgramming

We sometimes need to generate the QR code of an URL in our website. QR codes are scanned for verification, website login, opening websites and many things like that. In this article, we will see how to implement that. We are going to create a qrgenerator website in Django.

Example

Create a Django project and an app. Create a media folder at the same level of project and app.

Go to settings.py in the project folder and add the app name in INSTALLED_APPS and add this at the bottom −

MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'

Here we set up our media folder where we will store our QR code.

In urls.py of the project directory, add the following −

from django.contrib import admin
from django.urls import path,include
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
   path('admin/', admin.site.urls),
   path("",include("qrgenerator.urls"))
]
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

Here we defined the app urls and media folder url. qrgenerator is my app name.

Now install two libraries: PIL an qrcode.

pip install PIL
pip install qrcode

In app's urls.py

from django.urls import path,include
from . import views

urlpatterns = [
   path('', views.home,name='Home'),
]

Here we rendered our home view on main url.

In view.py, add the following lines −

from django.shortcuts import render
from .models import QrCode
# Create your views here.
def home(request):
   if request.method=="POST":
      Url=request.POST['url']
      QrCode.objects.create(url=Url)

   qr_code=QrCode.objects.all()
   return render(request,"home.html",{'qr_code':qr_code})

Here we took the url and then created a qrcode model's object and in the GET handler, we returned all our QR codes.

Create a "templates" folder in app directory (at the same level of migration folder) and add a file "home.html" in it with the following lines −

<!DOCTYPE html>
<html>
   <head>
      <title>tut</title>
   </head>
   <body>
      <form method="POST">
         {% csrf_token %}
         <input type="url" placeholder="URL PLEASE" requir
ed name="url">
         <button type= "submit" >get qrcode</button>
      </form>
      {% for qr in qr_code %}
      <img src="{{qr.image.url}}"/><br>
      {%endfor%}
   </body>
</html>

Here we created an input box to take the url and send it to the backend. Below <form>, we loop through each QR code object and show them as images.

Go to models.py and add the following lines −

from django.db import models
import qrcode
from PIL import Image, ImageDraw
from io import BytesIO
from django.core.files import File

# Create your models here.
import random
class QrCode(models.Model):
   url=models.URLField()
   image=models.ImageField(upload_to='qrcode',blank=True)

   def save(self,*args,**kwargs):
      qrcode_img=qrcode.make(self.url)
      canvas=Image.new("RGB", (300,300),"white")
      draw=ImageDraw.Draw(canvas)
      canvas.paste(qrcode_img)
      buffer=BytesIO()
      canvas.save(buffer,"PNG")
      self.image.save(f'image{random.randint(0,9999)}',File(buffer),save=False)
      canvas.close()
      super().save(*args,**kwargs)

Here we defined our own save method, which takes arguments. We used the qrcode library to generate the QR code and then we used the canvas to make it black and white. Then we added that QR code over the canvas and saved that as an image. We saved the image in the media folder and add it as a model instance.

Now, everything is set and you can proceed to check the output.

Output

raja
Published on 26-Aug-2021 13:15:12
Advertisements