0
votes

I will like to create a qrcode.png file and store it in my S3 bucket once a instance gets created in models.Model (using signals.py). With my code below I managed to create the qrcode__png file in my local base directory but it does not upload to my external S3 bucket or save in my models.Model class. HELP! Thanks. Signals.py

@receiver(post_save,sender=inventory)

def create__url_qr(sender, instance, created, **kwargs):

if created == True:
    qr = qrcode.QRCode(
            version=1,
            box_size=10,
            border=5)
    qr.add_data('/MyProperty/item/'+str(instance.id))
    qr.make(fit=True)
    im=qr.make_image(fill_color="black", back_color="white")
    im.save('qrcode___'+str(instance.id)+'.png', format="png")
    print('XXXX')
    print(im)
    print('XXXX')
    inst1 = inventory.objects.get(pk=instance.pk)        
    inst1.qr_code = im
    inst1.save() 
1

1 Answers

0
votes

You can read the file you wrote into a django.core.files.File object and then save that object to your model

import qrcode
from django.core.files import File
qr = qrcode.QRCode(
    version=1,
    box_size=10,
    border=5,
)
qr.add_data('/MyProperty/item/'+str(instance.id))
qr.make(fit=True)
im = qr.make_image(fill_color="black", back_color="white")
im.save('qrcode___'+str(instance.id)+'.png', format="png")
qr_file = File(open('qrcode___'+str(instance.id)+'.png'))
inst1 = inventory.objects.get(pk=instance.pk)
inst1.qr_code.save('qrcode___'+str(instance.id)+'.png', qr_file)

But you don't have to save it locally first, you could just write it to BytesIO and then save it

import qrcode
from io import BytesIO
from django.core.files import File
qr = qrcode.QRCode(
    version=1,
    box_size=10,
    border=5,
)
qr.add_data('/MyProperty/item/'+str(instance.id))
qr.make(fit=True)
im = qr.make_image(fill_color="black", back_color="white")
stream = BytesIO()
im.save(stream, format="png")
qr_file = File(stream)
inst1 = inventory.objects.get(pk=instance.pk)
inst1.qr_code.save('qrcode___'+str(instance.id)+'.png', qr_file)