简体   繁体   中英

Django storing image in static assets but not saving the file path in DB

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM