How to Create a QR Code Generator in Django

Faraz

By Faraz -

Learn to make a QR code generator in Django with our simple guide. Follow step-by-step instructions to add QR code functionality to your projects.


how-to-create-a-qr-code-generator-in-django.webp

QR codes are everywhere these days—from menus at restaurants to advertisements on billboards. These little squares pack a punch, enabling quick access to websites, contact information, and more with just a scan. With their increasing popularity, adding QR code generation to your web applications can significantly enhance user experience. In this guide, we will walk you through creating a QR code generator in Django, a powerful and flexible web framework.

Prerequisites

Before diving into the code, make sure you have a basic understanding of Django and some familiarity with Python. Here’s what you need:

  • Python installed on your computer
  • Basic knowledge of Django framework
  • A code editor (VS Code, PyCharm, etc.)

Setting Up Your Django Project

Installing Django

Before starting, ensure you have Python installed. You can install Django using pip:

pip install django

Creating a new Django project

Create a new Django project using the following command:

django-admin startproject qrcode_project

Setting up the project structure

Navigate into your project directory:

cd qrcode_project

Create a Django App

Create a new app within your project:

python manage.py startapp qr_generator

Adding the app to the project

Add qr_generator to INSTALLED_APPS in qrcode_project/settings.py:

INSTALLED_APPS = [
    'qr_generator',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Installing Required Libraries

We will use the qrcode library to generate QR codes. Install it using pip:

pip install qrcode[pil]

Building the QR Code Generator

Create Forms

In qr_generator, create a new file named forms.py and add the following function:

from django import forms

class QRCodeForm(forms.Form):
    text = forms.CharField(label='Text to Encode', max_length=255)

Creating a View for QR Code Generation

In qr_generator/views.py, create a new view that will handle the QR code generation logic:

import qrcode
from django.shortcuts import render
from .forms import QRCodeForm
from io import BytesIO
import base64


def generate_qr(request):
    qr_image_base64 = None
    if request.method == 'POST':
        form = QRCodeForm(request.POST)
        if form.is_valid():
            text = form.cleaned_data['text']
            qr = qrcode.QRCode(
                version=1,
                error_correction=qrcode.constants.ERROR_CORRECT_L,
                box_size=10,
                border=4,
            )
            qr.add_data(text)
            qr.make(fit=True)

            img = qr.make_image(fill='black', back_color='white')
            buffer = BytesIO()
            img.save(buffer, format='PNG')
            qr_image_base64 = base64.b64encode(buffer.getvalue()).decode()
    else:
        form = QRCodeForm()

    return render(request, 'index.html', {'form': form, 'qr_image_base64': qr_image_base64})

Creating Templates

Create a folder named templates inside your qr_generator app. Then create an index.html file. In qr_generator/index.html, add the following code to create a simple form:

<!DOCTYPE html>
<html>
<head>
    <title>QR Code Generator</title>
    <style>
        body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 0;
}
.container {
    width: 100%;
    max-width: 600px;
    margin: 50px auto;
    background: #fff;
    padding: 20px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
}
h1 {
    text-align: center;
    color: #333;
}
form {
    display: flex;
    flex-direction: column;
}
label {
    margin-bottom: 5px;
    color: #333;
}
input[type="text"] {
    width: 70%;
    padding: 10px;
    margin-bottom: 20px;
    border: 1px solid #ccc;
    border-radius: 4px;
}
button {
    padding: 10px;
    background-color: #007bff;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}
button:hover {
    background-color: #0056b3;
}
.qr-code {
    text-align: center;
    margin-top: 20px;
}
.qr-code img {
    max-width: 100%;
    height: auto;
}
.qr-code a {
    display: inline-block;
    margin-top: 20px;
    padding: 10px 20px;
    background-color: #007bff;
    color: #fff;
    text-decoration: none;
    border-radius: 4px;
}
.qr-code a:hover {
    background-color: #0056b3;
}
    </style>
</head>
<body>
    <div class="container">
        <h1>QR Code Generator</h1>
        <form method="post">
            {% csrf_token %}
            {{ form.as_p }}
            <button type="submit">Generate QR Code</button>
        </form>
        {% if qr_image_base64 %}
            <div class="qr-code">
                <h2>Your QR Code</h2>
                <img src="data:image/png;base64,{{ qr_image_base64 }}" alt="QR Code">
                <br>
                <a href="{% url 'generate_qr_code' %}">Generate another QR Code</a>
            </div>
        {% endif %}
    </div>
</body>
</html>

Configure URLs

In qr_generator, create a new file named urls.py and define the URL pattern:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.generate_qr, name='generate_qr_code'),
]

Include the app URLs in your project’s qrcode_project/urls.py:

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('qr_generator.urls')),
]

Step 3: Run the Django Server

Apply Migrations:

Apply migrations to set up the database (necessary even if not using a database for this app):

python manage.py migrate

Run the Development Server:

Start the Django development server:

python manage.py runserver

Access the QR Code Generator:

Open your web browser and navigate to http://127.0.0.1:8000/. You should see the QR code generator form. Enter some text, submit the form, and see the generated QR code displayed as an image.

Full Project Structure

qrcode_project/
├── qr_generator/
│   ├── migrations/
│   │   └── __init__.py
│   ├── templates/
│   │       └── index.html
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── forms.py
│   ├── models.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── qrcode_project/
│   ├── __init__.py
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── manage.py
└── db.sqlite3

Conclusion

Making a QR code generator in Django is a rewarding task. It shows how powerful and flexible Django can be. With this guide, you now know how to create, customize, and add QR code generation to your Django projects. This feature can make your apps more useful by allowing quick access to information. Keep exploring Django’s features to build even better applications.

FAQs

Q1. How do QR codes work?

QR codes store data in a two-dimensional grid that can be read by a camera or scanner.

Q2. Can I use this guide to add QR code generation to an existing Django project?

Yes, simply integrate the app and views into your existing project.

Q3. What are some common issues with QR code generation?

Common issues include incorrect data encoding and display problems due to missing libraries.

Q4. How can I customize the QR code's appearance?

Use the customization options in the qrcode library, such as color changes and error correction levels.

Q5. Are there alternatives to the qrcode library?

Yes, alternatives include libraries like pyqrcode and segno.

That’s a wrap!

I hope you enjoyed this article

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺