简体   繁体   中英

Django Python: Save Image when saving model to Amazon S3

I have my Django app configured to upload media files to AWS S3, this works for my uploads fine, what I am trying to do though is generate and save a QR code using python qrcode, but I can't find a way to do this in the docs. It currently saves to Heroku static, which doesn't work as it's only temporary and I have multiple dynos.

Here is my model so far:

class Car(models.Model):
   make= models.ForeignKey(Make,on_delete=models.CASCADE)
   number = models.IntegerField()
   deleted = models.BooleanField(default=False)
   qrcode = models.ImageField(upload_to="qrcodes",blank=True,null=True)

   def save(self, *args, **kwargs):
       import qrcode
       qrcode_img = qrcode.make('https://myurl.com/?c=' + str(self.id) + '&make=' + str(self.make.id))
       filepath = '/img/tmp/r' + str(self.make.id) + 't' + str(self.id) + '.png'
       filename = 'r' + str(self.make.id) + 't' + str(self.id) + '.png'

       buffered = BytesIO()
       qrcode_img.save(buffered, format="PNG")
       img_str = base64.b64encode(buffered.getvalue()).decode()
       self.qrcode = img_str

       super(Car, self).save(*args, **kwargs)



At the moment it is also ignoring the filename and filepath, only a string gets saved in my database whereas I want the file to upload to S3 and set the link to the file using the file path.

Thank you

I changed approach and used django-qr-codes which renders the QR code on the fly in the template

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM