Building an Online Barcode and QR Code Scanning App with Python Django

Barcodes and QR codes are essential tools across various industries, including healthcare, finance, and education. In this article, we’ll explore how to leverage Dynamsoft’s powerful barcode recognition technologies to create an online barcode and QR code scanning application using Python Django.

Prerequisites

To get started, ensure you have the following installed:

  • Django

    Install Django and verify the installation:

      python -m pip install Django
      python -m django --version
    
  • Dynamsoft Barcode Reader SDK v9.x

    Install the Dynamsoft Barcode Reader SDK:

      pip install dbr
    
  • SDK License

    To utilize the Dynamsoft Barcode Reader SDK, request a 30-day free trial license.

Supported Barcode Symbologies

Dynamsoft Barcode Reader SDK supports a wide range of barcode symbologies, including:

  • 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

Steps to Implement an Online Barcode and QR Code Reader in Python

Follow these steps to build your Django-based barcode and QR code reader:

  1. Initialize the Django Project

    Start by creating a new Django project:

     python -m django startproject djangodbr
    
  2. Create the scanbarcode App

    Add a new app to your project:

     python manage.py startapp scanbarcode
    
  3. Set Up Frontend with jQuery

    Copy jquery.min.js to the <project root>/static folder and create an index.html file in the <project root>/templates/scanbarcode directory. Use the following HTML and JavaScript code to handle file uploads:

     <!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>
    
  4. Define the View for the Web Page

    In scanbarcode/views.py, set the default web page to render the index.html:

     def index(request):
         return render(request, 'scanbarcode/index.html')
    
  5. Configure URL Patterns

    Create a urls.py file in the scanbarcode directory with the following URL patterns:

     from django.urls import path
    
     from . import views
        
     urlpatterns = [
       path('', views.index, name='index'),
       path('upload', views.upload, name="upload"),
     ]
    
  6. Integrate Custom URLs

    Modify the <project root>/djangodbr/urls.py file to include your app’s URLs:

     from django.contrib import admin
     from django.urls import path, include
        
     urlpatterns = [
         path('admin/', admin.site.urls),
         path('',  include('scanbarcode.urls'))
     ]
    
  7. Configure Template Directory

    Add the path of the template folder to the TEMPLATES setting in <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',
                 ],
             },
         },
     ]
    
  8. Implement Barcode and QR Code Scanning

    In scanbarcode/views.py, add the logic to scan barcodes and QR codes from uploaded images:

     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
        
     BarcodeReader.init_license("LICENSE-KEY")
     reader = BarcodeReader()
        
     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
    
  9. Deploy and Run the Django Barcode and QR Code Reader App

    Deploy the app by running the following commands:

     python manage.py makemigrations
     python manage.py migrate --run-syncdb
     python manage.py runserver
    

    Open a browser and navigate to 127.0.0.1:8000 to test the application.

    python django online barcode reader

Source Code

https://github.com/yushulx/python-barcode-qrcode-sdk/tree/main/examples/official/9.x/django