1

I was trying to create some products in ecommerce project in django and i had the data file ready and just wanted to loop throw the data and save to the database with Product.objects.create(image='', ...) but i couldnt upload the images from local directory to database!

I tried these ways:

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()

none worked for me.

Ivan Starostin
  • 8,798
  • 5
  • 21
  • 39

2 Answers2

2

After some searching, I got the answer. the code to use would be like this:

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()
Mehdi Mostafavi
  • 880
  • 1
  • 12
  • 25
0
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()

Got the answer from here

HarilalAV
  • 41
  • 1
  • 7