1
0
mirror of https://gitlab.com/free_zed/free_zed.gitlab.io.git synced 2024-06-18 14:32:20 +00:00
free_zed.gitlab.io/content/qrcode-generation-django.md
Freezed e9533e9974 🚧 Dust removal: QRcode generation on Django
Old tip needed to be actualised
2022-09-13 23:02:48 +02:00

77 lines
2.0 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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)