I am following this answer to fetch an image and store it in my model: Programmatically saving image to Django ImageField
I would like to store the image in static assets and also store the path to that image on the model attribute Product.large_image_file.
When I manually execute this code in shell_plus the image is successfully downloaded and stored and the path to the file is successfully saved in the DB.
When the code is executed with Django runserver, the image is downloaded and added to the static files but the path is not stored in the DB.
The exact same code works in shell_plus but does not work with runserver.
I used ipdb to step into the runserver environment and when I checked each.large_image_file it gives me the correct path but that path is not saved into the DB, even if I call each.save() manually.
Any ideas would be much appreciated!
def get_product_images():
# Download images from the URL and save it to static assets and the path to the model
product_photos = Product.objects.all()
for each in product_photos:
if each.large_image_url is not None and len(each.large_image_url) > 0:
try:
#check if the file is already stored
each.large_image_file.url
#error is raised if the file does not exist, retrieve and store the file
except ValueError:
result = urllib.request.urlretrieve(each.large_image_url)
each.large_image_file.save(os.path.basename(
each.large_image_url),
File(open(result[0], 'rb'))
)
each.save()