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.

2 Answers 2

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()
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.