Django.如何从views.py创建模型的新示例,并在模型中包含图像字段

7cwmlq89  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(114)

我正在尝试创建一个模型的新示例,其中有一个图像字段。我从一个表单中提取了一个PDF并将其转换为png文件格式,现在试图将png图像保存到模型数据库中,但得到错误“PngImageFile”对象没有属性“_committed”。我知道你不能保存图像直接到一个数据库,但我想知道你怎么能保存图像的媒体文件夹和保存图像的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

zpf6vheq

zpf6vheq1#

这就是我想到的
在“url.py”文件中,在“urlpatterns”的末尾添加以下行:

from djano.conf import settings
from django .conf.urls.static import static

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

字符串
现在你应该修改你的视图,将图像保存到介质文件夹,并将图像路径存储在模型中:

from django.core.files.uploadedfile import SimpleUploadedFile
import os

def upload_drawings(request):
    if request.method == "POST":
        form  = DrawingPDFForm(request.POST, request.FILES)
        drawing_name = request.POST['drawing_name']
        file = request.FILES['file']
        
        # Convert PDF to PNG
        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')
        
        # Save PNG to the media folder
        png_byt = buffer.getvalue()
        drawing_path = os.path.join('images', f'{drawing_name}.png')
        drawing_file = SimpleUploadedFile(drawing_path, png_byt, content_type='image/png')
        
        # Create and save the Drawing instance
        drawing = Drawing.objects.create(drawing_name=drawing_name, drawing=drawing_file)
        
        return HttpResponseRedirect('/upload_drawings')
    else:
        form = DrawingPDFForm()
        
    return render(request, 'upload_drawings.html', {'form': form})


并确保你已经在你的django项目中配置了媒体设置:

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')


我希望这对你有帮助。

相关问题