[英]Django storing image in static assets but not saving the file path in DB
我正在按照这个答案来获取图像并将其存储在我的模型中:以编程方式将图像保存到Django ImageField
我想将图像存储在静态资产中,并且还要将该图像的路径存储在模型属性Product.large_image_file上。
当我在shell_plus中手动执行此代码时,映像已成功下载并存储,并且文件路径已成功保存在DB中。
使用Django runserver执行代码时,将下载映像并将其添加到静态文件中,但是路径未存储在DB中。
完全相同的代码可在shell_plus中使用,但不适用于runserver。
我使用ipdb进入了运行服务器环境,当我检查each.large_image_file时,它为我提供了正确的路径,但是即使我手动调用each.save(),该路径也不会保存到数据库中。
任何想法将不胜感激!
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()
看来我在犯一个noob错误,并且在调用它时没有将Product类作为参数传递给get_product_images()。 我在外壳中手动导入了Product,这就是它在那里工作的原因。
现在可以从我的视图函数调用get_product_images(Product)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.