How to save or upload an image from LOCAL directory to ImageField of database object in DJANGO

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- first try:

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

Product.objects.create(image=image)

didnt work!!!

2- second try:

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

Product.objects.create(image=image)

3- third try:

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

🦋 Butterfly 🦋

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

Back to Top