【问题标题】:how to delete previously uploaded image from folder when the user change profile image in python?当用户在 python 中更改个人资料图像时,如何从文件夹中删除以前上传的图像?
【发布时间】: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


    【解决方案1】:

    有一个包 - django-unused-media 名称描述了它的作用

    访问文档: https://pypi.org/project/django-unused-media/

    【讨论】:

    • 好的。但这不会自动工作。我需要手动运行命令python manage.py cleaup_unsed_media来删除未使用的文件
    • 您可以让cronjobs在一定时间后自动运行命令。这是完成任务的最简单方法
    猜你喜欢
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 2021-07-03
    • 2015-10-28
    • 1970-01-01
    相关资源
    最近更新 更多