Search code examples
djangoamazon-s3qr-code

Django create QR code (Segno) and save to S3


I am seeking to create a QR code upon completion of a profile creation form for a user, and saving the QR image to a FileField. The FileField is also used for a profile_image field which already saves the image from the form to S3. I would like to do the same for the QR code (saving to S3 bucket).

Using Segno I am able to generate the QR code. How am I able to create an image of it and save it to S3 via the models.py FileField?

My code is as follows for the models.py and views.py files. Any help is appreciated.

models.py

class Profile(models.Model):
    def profile_path(instance, filename):
        return 'profile/{0}/{1}'.format(instance.profile_unique, filename)

    def qrcode_path(instance, filename):
        return 'profile/{0}/{1}'.format(instance.profile_unique, filename)
    #unique profile identification (alphanumeric string to be used on path for qrcode and profile image)
    profile_unique = models.CharField(max_length=50, default=0)
    #profile image filefield
    profile_image = models.FileField(upload_to=profile_path, default='')
    #qr code filefield
    qr_code = models.FileField(upload_to=qrcode_path, default='')

views.py

def add_profile(request):
    user = request.user
    userprofile = user.userprofile

    form = ProfileForm(request.POST or None, request.FILES or None)

    if form.is_valid():
        profile = form.save(commit=False)
        profile.profile_user_id = user.id
        profile.profile_unique = get_random_string(8)
        #segno
        qr = segno.make_qr('test')
        qr.save('example.png', scale=4)

        profile.qr_code = qr
        profile.save()


Solution

  • Managed to find the answer so for the benefit of anyone who needs it I've included it below:

    #qr code
    import io
    import segno
    from django.core.files.base import ContentFile
    
    #qr code
    out = io.BytesIO()
    qr = segno.make('test')
    qr.save(out, kind='png', dark='#000000', light=None, scale=3)
    
    filename = 'qr-'+profile.profile_unique+'.png'
    profile.qr_code.save(filename, ContentFile(out.getvalue()), save=False)
    profile.save()