Building Online Barcode and QR Code Scanning App with Python Django
Barcode and QR codes are widely used in many industries, such as healthcare, finance, and education. This article shares how to leverage Dynamsoft barcode recognition technologies to implement an online barcode and QR code scanning app with Python Django.
This article is Part 2 in a 3-Part Series.
Prerequisites
To create the online Barcode and QR code reader, we need to install Django and Dynamsoft Barcode SDK.
Python Django
pip install Django
Dynamsoft Python Barcode and QR Code SDK
pip install dbr
After installing the Python barcode SDK, you need to apply for a valid license to activate it.
reader.init_license("DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ==")
The supported barcode symbologies include:
- Linear Barcodes (1D) :
- Code 39 (including Code 39 Extended)
- Code 93
- Code 128
- Codabar
- Interleaved 2 of 5
- EAN-8
- EAN-13
- UPC-A
- UPC-E
- Industrial 2 of 5
- MSI Code
- 2D Barcodes :
- QR Code (including Micro QR Code)
- Data Matrix
- PDF417 (including Micro PDF417)
- Aztec Code
- MaxiCode (mode 2-5)
- DotCode
- Patch Code
- GS1 Composite Code
- GS1 DataBar :
- Omnidirectional
- Truncated
- Stacked
- Stacked Omnidirectional
- Limited
- Expanded
- Expanded Stacked
- Postal Codes :
- USPS Intelligent Mail
- Postnet
- Planet
- Australian Post
- UK Royal Mail
The Steps of Implementing Online Barcode and QR Code Reader in Python
-
Initialize the skeleton of the Django project:
python -m django startproject djangodbr
-
Add the start app module:
python manage.py startapp scanbarcode
-
Copy
jquery.min.js
to the<project root>/static
folder and then create anindex.html
file in the<project root>/templates/scanbarcode
directory. The following JavaScript code demonstrates how to upload files in Django project:<!DOCTYPE html> <head> <title>Django Online Barcode Reader</title> <meta charset="utf-8"> {% load static %} {% csrf_token %} <script type="text/javascript" src="{% static 'jquery-3.6.0.min.js' %}"></script> </head> <body> <input type="file" id="file" accept="image/*" /> <input id="btnUpload" type="button" value="Read Barcode" onclick="scanBarcode()"> <img id="image" /> <script type="text/javascript"> document.getElementById("file").addEventListener("change", function () { let file = this.files[0]; var fileReader = new FileReader(); fileReader.onload = function () { document.getElementById('image').src = fileReader.result; } fileReader.readAsDataURL(file); }); function scanBarcode() { let formData = new FormData(); formData.append('RemoteFile', document.getElementById('file').files[0], document.getElementById('file').files[0].name); let xhr = new XMLHttpRequest(); xhr.open('POST', '/upload', true); xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); xhr.onreadystatechange = function () { if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) { alert(xhr.responseText); } } xhr.send(formData); } function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } </script> </body> </html>
-
Go to
scanbarcode/views.py
to set the default web page:def index(request): return render(request, 'scanbarcode/index.html')
-
Create a
urls.py
file, which contains the URL patterns, in the<project root>/scanbarcode
directory:from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('upload', views.upload, name="upload"), ]
-
Configure the custom URL patterns in the
<project root>/djangodbr/urls.py
file:from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('scanbarcode.urls')) ]
-
Add the path of the template folder to
<project root>/djangodbr/settings.py
:TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
-
Scan barcode and QR code from the uploaded images in the
<project root>/scanbarcode/views.py
file:from django.http import HttpResponse, request from django import template from django.shortcuts import render import os from .models import Image from dbr import * import json reader = BarcodeReader() # Apply for a trial license: https://www.dynamsoft.com/customer/license/trialLicense?product=dbr reader.init_license("DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ==") def index(request): return render(request, 'scanbarcode/index.html') def upload(request): out = "No barcode found" if request.method == 'POST': filePath = handle_uploaded_file(request.FILES['RemoteFile'], str(request.FILES['RemoteFile'])) try: text_results = reader.decode_file(filePath) if text_results != None: out = '' for text_result in text_results: out += "Barcode Format : " + text_result.barcode_format_string + "\n" out += "Barcode Text : " + text_result.barcode_text + "\n" out += "------------------------------------------------------------\n" except BarcodeReaderError as bre: print(bre) return HttpResponse(out) return HttpResponse(out) return HttpResponse(out) def handle_uploaded_file(file, filename): if not os.path.exists('upload/'): os.mkdir('upload/') filePath = 'upload/' + filename with open(filePath, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) return filePath
Deploy and Run Django Barcode and QR Code Reader App:
python manage.py makemigrations
python manage.py migrate --run-syncdb
python manage.py runserver