Blog available for sell
This blog is available for sale. Please 'contact us' if interested.
Advertise with us
image   0   14490
Text to QR code image and QR code image to text generator in Python Django

In this article, we will generate the QR code image from some text and then generate the text from the QR code image. We used Django 3.2 and Python 3.9 for this article.

Text To QR Image

In Django, we can generate QRcode using Python PyQRCode Module. PyQRCode module is written in pure python. To install this module use the below command.

pip install PyQRCode

To get output as a QR image, we need to use the pypng module. pypng allows to read and write png files in python. Use the below command to install the pypng module.

pip install pypng

Follow the below steps to generate a QR image:

1. Create a qr_code.html file in your templates directory and write the below code to it.

<title>Text to QR image</title>
<form method="post" action="{% url 'qr_code'%}">
  {% csrf_token %}
<textarea rows="6" name="data" id="data" placeholder="Enter some text" cols="80" maxlength="1000"></textarea><be>
<input type="submit" name="action" value="Generate QR Code">
{% if qr_filename %}
<img src='/media/{{qr_filename}}' >
{% endif %}

2. To store the QR image in the project, we need to create a directory called media in the root project directory where is located. To server media files in Django, we need to add some configuration in the project’s file. Now, you need to add the below code to the file.


Here MEDIA_URL serves the media files and MEDIA_ROOT is the path to the root directory where all media files will store.

3. In your project's add the below code.

from django.conf import settings
from django.conf.urls.static import static urlpatterns=[
#your code
] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

4. Create a file in your app directory and add the below code.

from . import views
from django.urls import path

urlpatterns = [ path('qr-code',views.qr_code,name='qr_code' ) ]

5. Create a file in your app directory and add the below code.

from django.shorcuts import render
import pyqrcode
import png
def qr_code(request):
  context = {}
  if request.method == 'POST':
      data = request.POST["data"]
      img = pyqrcode.create(data)
      file_name = "qr.png"
      context["qr_filename"] = file_name
      img.png(settings.MEDIA_ROOT +file_name,scale=6)          
  return render(request, 'tools/qr_code.html', context)

    In the above code, we will store the QR code entered by a user in the data variable. Then in the next step, we have used 'pyqrcode.create(data)' to generate the QR object for the value stored in data. Next, we used the file_name and assigned it ‘qr.png’ to give a name to the QR image. To display the QR image on screen we are passing file_name in the context variable which contains the path of the QR image where it is stored.

    Pyqrcode returns the QR object, to get output as a QR image we need to pass the QR object to img.png(settings.MEDIA_ROOT + file_name, scale=6).

    QR Image To Text Generator

    We have successfully generated a QR code image. To read a QR image we need to install the pyzbar module and to process the image in the below code we need the Pillow module.

    To install the pyzbar and Pillow module use the below command.

    pip install pyzbar
    pip install Pillow

    Follow the below steps to read a QR image.

    1. Create qrcode_decoder.html in your templates directory of the project and add the below code to it.

    <form action="{% url 'qrcode_decoder' %}" method="post" enctype="multipart/form-data">
      {% csrf_token %}
              Upload QR Image:
              <input type="file" id="files" name="file" /><br><br>
              <button type="submit" class="btn btn-dark">Submit</button><br><br>
              <textarea rows=10 placeholder="output">{{decoded}}</textarea>

    2. Add the below code to the file.

    from . import views
    from django.urls import path

    urlpatterns = [ path('qr-code-decoder', views.qrcode_decoder, name='qrcode_decoder' ) ]

    3. Add the below code to the file

      from pyzbar.pyzbar import decode
      from PIL import Image def qrcode_decoder(request):
        if request.method == "POST" and request.FILES['file']:
            context = {}
            qr_image = request.FILES['file']
            context['decoded'] = decode([0].data.decode('ascii')      
            return render(request, 'tools/qrcode_decoder.html', context)   return render(request, 'tools/qrcode_decoder.html')

          First upload the file via the form. Get the file from request.Files[‘file’]. In the next step, we are decoding the image using the decode method. Next, we are passing the decoded text to the template.

          - Here is a list of some awesome python books
          - Host your Django Application for free on PythonAnyWhere.
          - If you want full control of your application and server, you should consider DigitalOcean.
          - Create a DigitalOcean account with this link and get $100 credits.
          - Purchase cheap domain names from NameCheap.

          Drop a mail in case of any query.

          This guest post was submitted by Poonam Panchal. To write an article for PythonCircle, drop us an email.

          cover image:
          image   0   14490
          0 comments on 'Text To Qr Code Image And Qr Code Image To Text Generator In Python Django'

          Related Articles:
          How to validate an uploaded image in Python Django
          Validating image before storing it in database or on file storage. Checking the size of uploaded image in python django. Checking the extension of uploaded image in python django. Checking the content size of uploaded image. Checking the mime-type of uploaded Image. Validating a malicious image before saving it. Using python-magic package...
          How to compress the uploaded image before storing it in Django
          Compressing an image in Django before storing it to the server, How to upload and compress and image in Django python, Reducing the size of an image in Django, Faster loading of Django template, Solving cannot write mode RGBA as JPEG error,...
          Python Script 17: Setting bing image of the day as desktop wallpaper
          Python Script to Set bing image of the day as desktop wallpaper, Automating the desktop wallpaper change to bing image of day using python code, changing desktop wallpaper using python, downloading an image using python code, updating the desktop wallpaper daily using python...
          Python Script 16: Generating word cloud image of a text using python
          word cloud python, generating a word cloud of a text using python code, python code to generate a word cloud image of a text. Using word frequencies to generate a word cloud image using a python script...
          DigitalOcean Referral Badge

          © 2022-2023 Python Circle   Contact   Sponsor   Archive   Sitemap