Django 加密文件字段与 Fernet 对象没有属性'_committed'发生



我将多个pdf上传文件从表单传递到视图中。(使用Uppy.XHRUpload(

我想在将它们保存到模型中之前对它们进行加密。

当我测试文件时,它们可以被加密并保存到一个文件中,然后读取和解密就可以了。

但当我试图添加到模型中时,我得到了:

'bytes' object has no attribute '_committed' occurred.

我可以下载加密文件,重新读取,然后保存,但那将是一种浪费。

我以为它会很简单:

if request.method == 'POST' and request.FILES:
files = request.FILES.getlist('files[]')
for index, file in enumerate(files):
f = Fernet(settings.F_KEY)
pdf = file.read()
encrypted = f.encrypt(pdf)
PDF_File.objects.create(
acct = a,
pdf = encrypted
)

模型。

class PDF_File(models.Model):
acct = models.ForeignKey(Acct, on_delete=models.CASCADE)
pdf = models.FileField(upload_to='_temp/pdf/')

谢谢你的帮助。

这是因为您无法将加密的(字节(保存到模型中

试试这个

from django.core.files.base import ContentFile
for index, file in enumerate(files):
f = Fernet(settings.F_KEY)
pdf = file.read()
encrypted = f.encrypt(pdf)
content_file = ContentFile(encrypted, name=your_filename)
PDF_File.objects.create(
acct = a,
pdf = content_file
)

此处的refhttps://docs.djangoproject.com/en/4.0/topics/http/file-uploads/

最新更新