mirror of
https://gitlab.com/free_zed/free_zed.gitlab.io.git
synced 2024-06-09 11:52:31 +00:00
WIP:QRcode on django note
This commit is contained in:
parent
cf9b67c72b
commit
c9b3103ac2
72
content/qrcode-generation-django.md
Normal file
72
content/qrcode-generation-django.md
Normal file
|
@ -0,0 +1,72 @@
|
|||
Title: Générer un QRcode dans Django
|
||||
Date: 2019-07-20 23:13
|
||||
Summary: Un générateur de code barre 2D dans une vue Django
|
||||
Category: Bloc-notes
|
||||
Tags: django, qrcode, web, dev, tdd, python
|
||||
Status: Draft
|
||||
Lang: fr
|
||||
|
||||
---
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
http://git.mf2i.fr/fred/confluent/tree/master/candidate/views.py
|
||||
https://github.com/lincolnloop/python-qrcode
|
||||
https://gilang.chandrasa.com/blog/generate-qr-code-in-django-model/
|
Loading…
Reference in New Issue
Block a user