【发布时间】:2021-12-02 15:20:39
【问题描述】:
我正在尝试将用户上传的图像转换为 PDF,然后将其存储到 mysql database 中的 ImageField 中,使用 form,但在尝试存储 PDF进入数据库
我的views.py是:
from django.core.files.storage import FileSystemStorage
from PIL import Image
import io
from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.core.files.base import ContentFile
def formsubmit(request): #submits the form
docs = request.FILES.getlist('photos')
print(docs)
section = request.POST['section']
for x in docs:
fs = FileSystemStorage()
print(type(x.size))
img = Image.open(io.BytesIO(x.read()))
imgc = img.convert('RGB')
pdfdata = io.BytesIO()
imgc.save(pdfdata,format='PDF')
thumb_file = ContentFile(pdfdata.getvalue())
filename = fs.save('photo.pdf', thumb_file)
linkobj = Link(link = filename.file, person = Section.objects.get(section_name = section), date = str(datetime.date.today()), time = datetime.datetime.now().strftime('%H:%M:%S'))
linkobj.save()
count += 1
size += x.size
return redirect('index')
我的models.py:
class Link(models.Model):
id = models.BigAutoField(primary_key=True)
person = models.ForeignKey(Section, on_delete=models.CASCADE)
link = models.ImageField(upload_to= 'images', default = None)
date = models.CharField(max_length=80, default = None)
time = models.CharField(max_length=80,default = None)
我得到的错误是:
AttributeError: 'str' object has no attribute 'file'
我尝试过的其他方法:
1) linkobj = Link(link = thumb_file, person = Section.objects.get(section_name = section), date = str(datetime.date.today()), time = datetime.datetime.now().strftime('%H:%M:%S'))
上述方法的结果:
1)thumb_file 不会抛出错误,而是不会在数据库中存储任何内容
我注意到的几点:
1)文件被正确存储到媒体文件夹中,即:我可以看到 pdf 被存储在媒体文件夹中
我该如何解决这个问题?谢谢
【问题讨论】: