2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[python] Djangoでurlを取得し、QRCodeを作成する

Posted at

はじめに

QRCodeによる現場管理を構想しているので、DjangoでQRCodeの生成方法をまとめておく。
こういうのは知ってて利用するよりも、その都度、調べるしかないですね。

環境

Django 3.1.13
python 3.9
qrcode 7.3.1

pip install qrcode

Code

QRCode作成

view.py
import qrcode
import qrcode.image.svg
from io import BytesIO


def show_work(request, work_id):
    work = Work.objects.get(pk=work_id)

    url = request.build_absolute_uri()
    # 表示されるurlを取得

    factory = qrcode.image.svg.SvgImage
    img = qrcode.make(url, image_factory=factory, box_size=10)
    # box_sizeでイメージの大きさを調整

    stream = BytesIO()
    img.save(stream)
    svg = stream.getvalue().decode()
    return render(request, 'show_work.html', {"work": work, "svg" : svg})

QRCodeを表示

show_work.html
    {{svg|safe}}

結果

image.png
localhostなのでなにも表示はされないですが、これで簡単にurlのQRCodeを作れます。

参考

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?