【发布时间】:2020-11-25 17:34:39
【问题描述】:
我有一个用户个人资料页面,用户可以从中更新其详细信息并更改个人资料图片。图片上传工作正常。但我希望当用户更改其个人资料图像时。之前上传的图片应该从文件夹中删除。
我有一个 UserProfile 模型,它的 OneToOneField() 关联到 user_auth 表
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_img = models.ImageField(upload_to='ProfileImg')
views.py
profile_img = request.FILES['profile-upload']
if profile_img.name.endswith(tuple(ALLOWED_EXTENTIONS)):
if user.userprofile.profile_img is not None:
os.remove(user.userprofile.profile_img.name) <---------this solution is not working
user.userprofile.profile_img = profile_img
user.save()
How to delete old image when update ImageField?
我尝试了这个解决方案,但它引发了一个错误:
Exception Type: FileNotFoundError
Exception Value:
[WinError 3] The system cannot find the path specified: 'ProfileImg/model-5.jpg'
我已经重新检查了文件夹并且图像仍然存在。 我不知道我哪里错了。 任何形式的帮助将不胜感激
【问题讨论】:
标签: python django python-2.7 django-models django-views