pro[zind]

Générer un QRcode dans Django

dans Bloc-notes

🚧 need to be refreshed 🚧

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: