如何在DJANGO中将LOCAL目录下的图像保存或上传到数据库对象的ImageField中

jaxagkaj  于 2022-12-24  发布在  Go
关注(0)|答案(2)|浏览(147)

我试图在Django的电子商务项目中创建一些产品,我已经准备好了数据文件,只是想循环抛出数据,并保存到数据库与Product.objects.create(image='', ...),但我无法从本地目录上传到数据库的图像!
我试过这些方法:
1

with open('IMAGE_PATH', 'rb') as f:
     image = f.read()

Product.objects.create(image=image)

2

image = open('IMAGE_PATH', 'rb')

Product.objects.create(image=image)

3

module_dir = dir_path = os.path.dirname(os.path.realpath(__file__))

for p in products:
    file_path = os.path.join(module_dir, p['image'])
    Product.objects.create()

     product.image.save(
            file_path,
            File(open(file_path, 'rb'))
            )

     product.save()

对我都不管用。

x6492ojm

x6492ojm1#

经过一番搜索,我得到了答案。要使用的代码如下:

from django.core.files import File

for p in products:
    product = Product.objects.create()
    
    FILE_PATH = p['image']

    local_file = open(f'./APP_NAME/{FILE_PATH}', "rb")
    djangofile = File(local_file)
    product.image.save('FILE_NAME.jpg', djangofile)
    local_file.close()
41zrol4v

41zrol4v2#

from django.core.files import File  
import urllib

result = urllib.urlretrieve(image_url) # image_url is a URL to an image

model_instance.photo.save(
    os.path.basename(self.url),
    File(open(result[0], 'rb'))
    )

self.save()

here获得答案

相关问题