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 =


didnt work!!!

2- second try:

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


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'])
            File(open(file_path, 'rb'))

🦋 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)'FILE_NAME.jpg', djangofile)
from django.core.files import File  
import urllib

result = urllib.urlretrieve(image_url) # image_url is a URL to an image
    File(open(result[0], 'rb'))

Got the answer from here

Back to Top