2017-02-23 86 views
0

我必須從我的應用程序中刪除圖像。必須從「媒體」文件(我的項目中的目錄)和數據庫中刪除圖像。 這裏是我的類刪除圖像在Django中刪除圖像

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() 

誰能幫助我?我看到所有類似的問題和答案,但不能解決這個問題...... :)

+1

可能重複[如何更新ImageField時刪除舊圖像?](http://stackoverflow.com/questions/2878490/how-to-delete-old-image-when-update-imagefield) –

回答

0

這是我的案件的答案。 :)

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類中。

希望,這將是有益的! :)