Trying to generate a qrcode dynamically and have it displayed in the template. Do not want to save it.
Error:
‘utf-8’ codec can’t decode byte 0x89 in position 0: invalid start byte
views.py
from io import BytesIO
def generate_qr_code (request):
fish = CustomUser.objects.get(username='jslovern391')
img = qrcode.make(f'{get_current_site}/accounts/signup/{fish.alias_name}')
stream = BytesIO()
img.save(stream)
context = {
'qrcode': stream.getvalue().decode()
}
return render(request, 'accounts/qrcode.html', context=context)
urls.py
path('qrcode/', views.generate_qr_code, name='qrcode'),
template:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fisher QRCodet</title>
</head>
<body>
<h1>Fisher QRCode</h1>
<img src="{{ qrcode }}">
</body>
</html>
If you’re going to include the data for the image inline in the src tag, it needs to be of the format:
<img src="data:image/png;base64,{{ base64_encoded_qrcode }}"/>
1 Like
The page renders now, but it does not show the qrcode.
If I do a base64_encoded_qrcode.save, it saves it as a png. Which should mean it is generating it?
I used the name base64_encoded_qrcode
as an indication that you need to convert the binary qrcode data to its base64 representation and you use it in the src
attribute - not that you actually create something called base64_encoded_qrcode.
So with this code, I need to put it into base64, is that correct? If so, how do I do that?
def fisher_qrcode(request):
fish = CustomUser.objects.get(username='xxxx')
base64_encoded_qrcode = qrcode.make(f'http://127.0.0.1:8000/accounts/signup/{fish.alias_name}')
context = {
'qrcode': base64_encoded_qrcode
}
return render(request, 'accounts/fisher_qrcode.html', context=context)
I did it the other way around. I passed the string to the template and then used js to covert it to a qrcode.
Thank you @KenWhitesell , the template example was what I needed.