【问题标题】:Delete image in Django在 Django 中删除图像
【发布时间】:2017-02-23 16:34:07
【问题描述】:

我必须从我的应用程序中删除图像。必须从“媒体”文件(我的项目中的目录)和数据库中删除图像。 这是我的班级 DeleteImage

class DeleteImage(DeleteView):
    template_name = 'layout/delete_photo.html'
    model = Profile
    success_url = reverse_lazy('git_project:add_photo')

这是 HTML 页面

{% extends 'layout/base.html' %}
{% block body %}
{% if allprofiles %}
<ul>
{% for profile in allprofiles %}
    <li>
        <img src="/{{ profile.image }}" height="75" />
        <a href="{% url 'git_project:delete_photo' user.profile.id %}">Delete</a>
    </li>
</ul>
{% endfor %}
{% endif %}
{% endblock %}

不知道你是否需要models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.FileField()

谁能帮我解决这个问题?我看到了所有类似的问题和答案,但无法解决这个问题...... :)

【问题讨论】:

标签: python django


【解决方案1】:

这是适用于我的情况的答案。 :)

def delete(self, *args, **kwargs):
    # You have to prepare what you need before delete the model
    storage, path = self.image.storage, self.image.path
    # Delete the model before the file
    super(Profile, self).delete(*args, **kwargs)
    # Delete the file after the model
    storage.delete(path)

必须在model.py的Profile类中添加。

希望对您有所帮助! :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多