Title: Générer un QRcode dans Django
Date: 2019-07-20 23:13
Modified: 2021-11-28 02:00
Summary: Un générateur de code barre 2D dans une vue Django
Category: Bloc-notes
Tags: django, qrcode, web, dev, python
Status: Published

🚧 _need to be refreshed_ 🚧

```python
from base64 import b64encode
import io
import qrcode

from django.urls import reverse
from django.views.generic import DetailView

from foobar.models import Foobar


class FoobarDetail(DetailView):
    """ Detail view of a Foobar """

    model = Foobar
    pk_url_kwarg = "foobar_id"

    def get_context_data(self, **kwargs):
        """ Add a Base64 encoded image (QRcode) containing URL to foobar page """

        new_qrcode = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_H,
            box_size=6,
            border=0,
        )

        url_host = self.request.get_host()
        url_protocol = "http://"

        if self.request.is_secure():
            url_protocol = "https://"

        new_qrcode.add_data(
            "{protocol}{host}{path}".format(
                protocol=url_protocol,
                host=url_host,
                path=reverse(
                    "foobar:form",
                    kwargs={"foobar_id": self.kwargs["foobar_id"]},
                ),
            )
        )
        new_qrcode.make(fit=True)
        qr_image = new_qrcode.make_image()

        qr_byte_image = io.BytesIO()
        qr_image.save(qr_byte_image, format="PNG")
        qr_byte_image = qr_byte_image.getvalue()
        qr_b64_image = "data:image/png;base64,{}".format(
            b64encode(qr_byte_image).decode()
        )

        context = super().get_context_data(**kwargs)
        context["qrcode"] = qr_b64_image

        return context
```

---

Refs:

- Internal `candidate/views.py`
- [`lincolnloop/python-qrcode`](https://github.com/lincolnloop/python-qrcode)
- [_Generate QR Code In Django Model_](https://gilang.chandrasa.com/blog/generate-qr-code-in-django-model/) by [_Gilang Chandrasa_](https://gilang.chandrasa.com/) (16 Nov 2015)
