Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
QR code generating website in Django
We sometimes need to generate QR codes for URLs in our Django websites. QR codes are scanned for verification, website login, opening websites and many other purposes. In this article, we will see how to implement a QR code generator website in Django.
Setting Up the Django Project
First, create a Django project and an app. Create a media folder at the same level as your project and app directories.
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/'
This sets up our media folder where we will store our generated QR codes.
URL Configuration
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. Replace qrgenerator with your actual app name.
Installing Required Libraries
Install the required libraries for image processing and QR code generation ?
pip install Pillow pip install qrcode
App URL Configuration
In the app's urls.py ?
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='Home'),
]
Creating Views
In views.py, add the following code ?
from django.shortcuts import render
from .models import QrCode
def home(request):
if request.method == "POST":
url = request.POST['url']
QrCode.objects.create(url=url)
qr_codes = QrCode.objects.all()
return render(request, "home.html", {'qr_code': qr_codes})
This view handles both GET and POST requests. When a URL is submitted via POST, it creates a new QrCode object. The view then renders all existing QR codes on the homepage.
Creating Templates
Create a templates folder in your app directory and add a file home.html with the following content ?
<!DOCTYPE html>
<html>
<head>
<title>QR Code Generator</title>
</head>
<body>
<h1>QR Code Generator</h1>
<form method="POST">
{% csrf_token %}
<input type="url" placeholder="Enter URL" required name="url">
<button type="submit">Generate QR Code</button>
</form>
<h2>Generated QR Codes</h2>
{% for qr in qr_code %}
<div>
<p>URL: {{ qr.url }}</p>
<img src="{{ qr.image.url }}" alt="QR Code"/>
</div>
<hr>
{% endfor %}
</body>
</html>
Creating the QR Code Model
Go to models.py and add the following code ?
from django.db import models
import qrcode
from PIL import Image, ImageDraw
from io import BytesIO
from django.core.files import File
import random
class QrCode(models.Model):
url = models.URLField()
image = models.ImageField(upload_to='qrcode', blank=True)
def save(self, *args, **kwargs):
# Generate QR code
qrcode_img = qrcode.make(self.url)
# Create canvas and paste QR code
canvas = Image.new("RGB", (300, 300), "white")
canvas.paste(qrcode_img)
# Save to buffer
buffer = BytesIO()
canvas.save(buffer, "PNG")
# Save image to model
filename = f'qrcode_{random.randint(0, 9999)}.png'
self.image.save(filename, File(buffer), save=False)
canvas.close()
buffer.close()
super().save(*args, **kwargs)
This model overrides the save() method to automatically generate a QR code image when a new QrCode object is created. The QR code is generated using the qrcode library and saved as a PNG image.
Running Migrations
Don't forget to create and apply migrations for your model ?
python manage.py makemigrations python manage.py migrate
How It Works
The QR code generation process works as follows:
- User enters a URL in the form and submits it
- Django creates a new QrCode model instance
- The model's custom save() method generates a QR code image
- The QR code is saved to the media folder
- All generated QR codes are displayed on the homepage
Conclusion
This Django application demonstrates how to create QR codes for URLs using the qrcode and Pillow libraries. The custom model save method automatically generates and stores QR code images, making it easy to create a functional QR code generator website.
