1

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()
  • 1
    The except shouldn't be a generic one. Please specify the one you want to catch (I think AttributeError). I am not saying that's the problem here, just pointing out a habit that you should get rid of – e4c5 Jan 10 '17 at 05:33
  • check the instance pk. and also see if you have any transactions – e4c5 Jan 10 '17 at 05:33
  • @e4c5 yes just updated with that suggestion and a few more details. This function works perfectly in the shell but is still not storing the path on the model attribute each.large_image_file – Daniel Vitiello Jan 10 '17 at 15:53

1 Answers1

0

It appears I was making a noob mistake and not passing the Product class as an argument into get_product_images() when calling it. I manually imported Product in the shell so that is why it worked there.

Calling get_product_images(Product) from my view function now works.