Reputation: 85
I have to delete image from my app. Image has to be deleted from "media" file (directory inside my project) and from database. Here is my class DeleteImage
class DeleteImage(DeleteView):
template_name = 'layout/delete_photo.html'
model = Profile
success_url = reverse_lazy('git_project:add_photo')
This is HTML page
{% 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 %}
I don't know if you need models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.FileField()
Can anyone help me with this? I saw all similar Questions and Answers but can't figure this issue out... :)
Upvotes: 3
Views: 2434
Reputation: 85
This is the answer that works in my case. :)
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)
It has to be added in Profile class in model.py.
Hope, it will be helpfull! :)
Upvotes: 3