当用户在python中更改配置文件图像时,如何从文件夹中删除以前上载的图像?
我有一个用户配置文件页面,用户可以在其中更新其详细信息并更改配置文件图像。图像上传工作正常。但当用户更改其配置文件图像时,我希望这样做。以前上载的图像应从文件夹中删除 我有一个当用户在python中更改配置文件图像时,如何从文件夹中删除以前上载的图像?,python,django,python-2.7,django-models,django-views,Python,Django,Python 2.7,Django Models,Django Views,我有一个用户配置文件页面,用户可以在其中更新其详细信息并更改配置文件图像。图像上传工作正常。但当用户更改其配置文件图像时,我希望这样做。以前上载的图像应从文件夹中删除 我有一个UserProfile模型,它有一个与user\u auth表关联的OneToOneField() models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) p
UserProfile
模型,它有一个与user\u auth
表关联的OneToOneField()
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_img = models.ImageField(upload_to='ProfileImg')
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()
views.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_img = models.ImageField(upload_to='ProfileImg')
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()
我已经重新检查了文件夹,图像仍然在那里。
我不知道我哪里出错了。
任何形式的帮助都将不胜感激有一个软件包-
django unused media
name描述了它的功能
访问文档:
好的。但这并不是自动的。我需要手动运行命令
python manage.py cleaup\u unsed\u media
删除未使用的文件您可以让cronjobs在一定时间后自动运行该命令。这是完成任务最简单的方法