2017-02-23 7 views
0

私のアプリから画像を削除する必要があります。イメージは「メディア」ファイル(プロジェクト内のディレクトリ)とデータベースから削除する必要があります。 はここに私のクラスDeleteImageある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 %} 

あなたは

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

は、誰もがこれで私を助けることができる

models.pyの必要がある場合、私は知らないのですか?私はすべての同様の質問と回答を見ましたが、この問題を把握することはできません... :)

+1

[イメージフィールドの更新時に古いイメージを削除する方法](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クラスに追加する必要があります。

希望、それは役に立ちます! :)