我正在尝试根据模型生成二维码。我在 Heroku 托管该应用程序并使用 AWS S3 作为存储。 S3 存储与其他模型元素配合得很好,只是 QR 代码生成模型出现了问题。我使用此链接作为引用: https://gilang.chandrasa.com/blog/generate-qr-code-in-django-model/ 我的模型是:
class BusinessQRCode(models.Model):
business = models.ForeignKey(Business, null=True)
location_name = models.CharField(max_length=255)
qrcode = models.ImageField(upload_to='documents/{}'.format(time.strftime("%Y/%m/%d")), blank=True, null=True)
def save(self):
super(BusinessQRCode, self).save()
self.generate_qrcode()
def generate_qrcode(self):
from activation.models import RandomFileName
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data('Some data')
qr.make(fit=True)
filename = 'qrcode-%s.png' % self.id
img = qr.make_image()
from django.conf import settings
img.save(settings.MEDIA_ROOT + filename)
# reopen = open(settings.MEDIA_ROOT + filename, "rb")
# django_file = File(reopen)
self.qrcode.save(filename,img, save=True)
上面的代码给了我这个错误:
TypeError
TypeError: seek() takes exactly 2 arguments (3 given)
我也尝试过使用注释代码,即打开文件并尝试保存它,但它不起作用,它只是永远不会停止加载。我的意思是最后这部分代码:
reopen = open(settings.MEDIA_ROOT + filename, "rb")
django_file = File(reopen)
self.qrcode.save(filename,django_file, save=True)
我做错了什么?
最佳答案
I have tried using the commented code as well, that is opening the file and than trying to save it, but it doesnt work, it just never stops loading.
我认为最后一种方法应该可行,但由于您在保存 ImageField 时使用 save=True
,这也会触发父模型的 save()
方法。所以你最终会陷入无限循环。
更改保存图像字段和模型的顺序。
def save(self):
# Generate qrcode before calling super.save
self.generate_qrcode()
super(BusinessQRCode, self).save()
def generate_qrcode(self):
...
with open(settings.MEDIA_ROOT + filename, "rb") as reopen:
django_file = File(reopen)
self.qrcode.save(filename,django_file, save=False)
关于python - Django QR 代码生成 PIL 图像使用 S3 保存不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42042424/