[英]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.