我已成功在我的网络应用程序中实现了双因素身份验证包,但是我想在用户登录时向模板显示二维码,但目前无法这样做。
此软件包使用向导表单,当提示用户设置两个因素时,在设置过程中会显示二维码,以便他们在所选设备上扫描,但不确定如何使用二维码以便以后在另一个模板中使用。
我从向导模板中找到了以下代码段,我尝试使用它,但说找不到页面:
<div class="d-flex justify-content-center">
<p><img src="{{ QR_URL }}" alt="QR Code" /></p>
</div>
找不到页面错误
Using the URLconf defined in wfi_workflow.urls, Django tried these URL patterns, in this order:
admin/
account/login/ [name='login']
account/two_factor/setup/ [name='setup']
account/two_factor/qrcode/ [name='qr']
The current path, account/two_factor/qrcode/, matched the last one.
但是我可以通过管理面板查看用户的二维码:
有人知道如何仅在另一个模板中显示二维码吗?如果需要更多信息,请告诉我。谢谢
要在模板中显示二维码,您可以像这样获取视图中的图像网址:
device = TOTPDevice.objects.get(user=obj)
if device:
qr_code_url = reverse('admin:%s_%s_qrcode' % (TOTPDevice._meta.app_label, TOTPDevice._meta.model_name), args=[device.pk])
或直接svg图像:
device = TOTPDevice.objects.get(user=obj)
if device:
import qrcode
import qrcode.image.svg
img = qrcode.make(device.config_url, image_factory=qrcode.image.svg.SvgImage)
要将 QR 码合并到模板中,您需要将其创建为基本 64 编码图像,并将其传递到上下文数据中的模板:
views.py
import qrcode
from io import BytesIO
from base64 import b64encode
qr_code_img = qrcode.make(device.config_url) # This should be the device for which you want to generate the QR code
buffer = BytesIO()
qr_code_img.save(buffer)
buffer.seek(0)
encoded_img = b64encode(buffer.read()).decode()
qr_code_data = f'data:image/png;base64,{encoded_img}'
return render(request, 'template.html', {'qr_code_data': qr_code_data})
模板.html
<img src="{{ qr_code_data }}" />
您可以使用以下代码在 Django 模板中显示二维码。 *我使用 Django 双因素身份验证:
# "views.py"
from django.shortcuts import render
from django_otp.plugins.otp_totp.models import TOTPDevice
import qrcode
from io import BytesIO
from base64 import b64encode
def test(request):
obj = TOTPDevice.objects.get(user_id=request.user.id)
qr_code_img = qrcode.make(obj.config_url)
buffer = BytesIO()
qr_code_img.save(buffer)
buffer.seek(0)
encoded_img = b64encode(buffer.read()).decode()
qr_code_data = f'data:image/png;base64,{encoded_img}'
return render(request, 'index.html', {'qr_code_data': qr_code_data})
{% "index.html" %}
<img src="{{ qr_code_data }}" />