Generate a QR code programmatically in Python
Tags: python, django
Published: 2023-01-28 12:53:08

---
title: Generate a QR code programmatically in Python
published: true
date: 2023-01-28 12:52:17 UTC
tags: Python,Django
canonical_url: https://www.rockandnull.com/generate-qr-code-python/
---

 ![Generate a QR code programmatically in Python](https://images.unsplash.com/photo-1625038624658-01a222d8fb8e?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwxMTc3M3wwfDF8c2VhcmNofDExfHxxcnxlbnwwfHx8fDE2NzQ5MTAyNDY&ixlib=rb-4.0.3&q=80&w=2000)

Nowadays, QR codes are everywhere. From the restaurant menu to graffiti, it's the easiest way to place an internet link into the physical world.

There are countless websites only that allows you to create QR codes using their services. Some even offer an API to let you create a QR code programmatically. In case your Python/Django project needs a way to quickly create QR codes programmatically, an external API may be overkill.

You see, there are quite a few open-source Python libraries that offer this programmatic creation of QR codes with a few lines of code.

In this post, we'll show how to create programmatically a QR code and then download that code as an image.

## Set up

The QR library that we will use in this post is [qrcode](https://pypi.org/project/qrcode/). For image generation, we will use the popular [pillow](https://pypi.org/project/Pillow/) library. To install both of them in one line, just run:

```
pip install qrcode[pil]
```

## Sample code

In the following snippet, we have a sample Django view that will generate and prompt the user to download a QR code in a PNG format that links to the URL of the current page.

```
class QrCodeView(View):

    def get(self, request):
        # 1.
        path = request.GET["path"]
        url = f"https://{get_current_site(self.request).domain}{path}"

        # 2.
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr.add_data(url)
        qr.make(fit=True)
        
        # 3.
        img = qr.make_image(fill_color="black", back_color="white")
        temp_file = NamedTemporaryFile(delete=True)
        img.save(temp_file.name)

        # 4.
        response = HttpResponse(temp_file)
        response["Content-Disposition"] = f"attachment; filename=qr.png"
        return response

```

1. This is how we get the absolute URL to the existing page. Remember that the usual Django utilities (e.g. `reverse()`) return relative URLs. 
2. We use the `qrcode` library to create the QR code in memory. The library offers multiple parameters to customize the generated QR code. These are some of the default ones, briefly explained:  
- `version`: Controls the size of the QR Code, `version=1` is a 21x21 matrix.  
- `error_correction`: The amount of "backup" pixels to be added in the image in case there's a section that is dirty or damaged ([more details](https://blog.qrstuff.com/general/qr-code-error-correction)).  
- `box_size`: Number of pixels for each "box" of the QR code.  
- `border`: How thick the border should be.  
I strongly urge you to check the library's [documentation](https://pypi.org/project/qrcode/) for a list of all the available parameters to customize your QR code.
3. Use the `pillow` library to convert that QR code into a PNG image and store it in a temporary file.
4. Prompt the user to download the PNG image file.

Hopefully, this was a quick and easy intro to how to create and download a QR code in Django programmatically.

Happy coding!