Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当用户在python中更改配置文件图像时,如何从文件夹中删除以前上载的图像?_Python_Django_Python 2.7_Django Models_Django Views - Fatal编程技术网

当用户在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在一定时间后自动运行该命令。这是完成任务最简单的方法