简体   繁体   English

Django将图像存储在静态资产中,但不将文件路径保存在DB中

[英]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 我正在按照这个答案来获取图像并将其存储在我的模型中:以编程方式将图像保存到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. 我想将图像存储在静态资产中,并且还要将该图像的路径存储在模型属性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. 当我在shell_plus中手动执行此代码时,映像已成功下载并存储,并且文件路径已成功保存在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. 使用Django runserver执行代码时,将下载映像并将其添加到静态文件中,但是路径未存储在DB中。

The exact same code works in shell_plus but does not work with runserver. 完全相同的代码可在shell_plus中使用,但不适用于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. 我使用ipdb进入了运行服务器环境,当我检查each.large_image_file时,它为我提供了正确的路径,但是即使我手动调用each.save(),该路径也不会保存到数据库中。

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. 看来我在犯一个noob错误,并且在调用它时没有将Product类作为参数传递给get_product_images()。 I manually imported Product in the shell so that is why it worked there. 我在外壳中手动导入了Product,这就是它在那里工作的原因。

Calling get_product_images(Product) from my view function now works. 现在可以从我的视图函数调用get_product_images(Product)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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