15.07.2021       Выпуск 395 (12.07.2021 - 18.07.2021)       Статьи

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 PythonPyQRCode Module. PyQRCode module is written in pure python. To install this module use the below command.

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

Follow the below steps to generate a QR image:

1. Create aqr_code.htmlfile 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 calledmediain the root project directory where manage.py is located. To server media files in Django, we need to add some configuration in the project’s settings.py file. Now, you need to add the below code to the settings.py file.


HereMEDIA_URLserves the media files andMEDIA_ROOTis the path to the root directory where all media files will store.

3. In your project's urls.py 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 urls.py 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 views.py 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 toimg.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 installthe pyzbar moduleand to process the image in the below code we needthe Pillow module.

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

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 urls.py 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 views.py 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(Image.open(qr_image))[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: https://unsplash.com/@markuswinkler

Разместим вашу рекламу

Пиши: mail@pythondigest.ru

Нашли опечатку?

Выделите фрагмент и отправьте нажатием Ctrl+Enter.

Система Orphus