我正在尝试创建一个包含图像字段的模型的新实例。我从表单中获取 PDF 并将其转换为 png 文件格式,现在尝试将 png 图像保存到模型数据库,但收到错误“PngImageFile”对象没有属性“_commissed”。我知道您无法将图像直接保存到数据库,但我想知道如何将图像保存到媒体文件夹并将图像 url 路径保存到数据库中的图像?非常感谢帮助。
这是我要在 PDF 中获取的表单(forms.py)
class DrawingPDFForm(forms.Form):
drawing_name = forms.CharField(max_length=50)
file = forms.FileField()
这是我将 PDF 转换为 PNG 的视图,然后创建新的模型实例以保存到数据库(views.py)
def upload_drawings(request):
if request.method == "POST":
form = DrawingPDFForm(request.POST, request.FILES)
drawing_name = request.POST['drawing_name']
file = request.FILES['file']
pdf_byt = file.read()
pdf_content = BytesIO(pdf_byt)
pdf_content.seek(0)
pdf_converted = convert_from_bytes(pdf_content.read(), poppler_path=r"C:\Python\Python\Programs\plant_locator\poppler\poppler-23.07.0\Library\bin")
buffer = BytesIO()
pdf_converted[0].save(buffer, 'png')
png_byt = buffer.getvalue()
my_string = base64.b64encode(png_byt)
pdf_png_byt_decode = base64.b64decode(my_string)
png = Image.open(BytesIO(pdf_png_byt_decode))
drawing = Drawing.objects.create(drawing_name=drawing_name, drawing=png)#error occurs here as #expected
drawing.save()
return HttpResponseRedirect('/upload_drawings')
else:
form = DrawingPDFForm()
return render(request, 'upload_drawings.html', {'form':form})
这是我的模型,我正在尝试创建 (models.py) 的新实例
from django.db import models
class Drawing(models.Model):
drawing_name = models.CharField('Drawing Name', max_length=50)
drawing = models.ImageField(null=True, blank=True, upload_to="images/")
def __str__(self):
return self.drawing_name