4 albums in database
4 pictures in media
press delete, confirm delete page opens.
confirm delete, 1 album is deleted
picture associated with album is deleted in media
#power shell
pip install django-cleanup
#project1/settings
INSTALLED_APPS = (
...
'django_cleanup', # should go after your apps
)
---------------------------------------------
#music/templates/index
{% extends 'music/base.html' %}
{% block title %}Albums{% endblock %}
{% block body %}
<div class="container-fluid">
<div class="row">
{% for album in object_list %}
<div class="col" style="margin-left: auto; margin-right: auto; margin-top: 5px; margin-bottom: 5px;">
<div class="card" style="width: 200px;">
<img src="{{album.album_logo.url}}" class="card-img-top" style="height: 150px" alt="{{album.album_title}}">
<div class="card-body">
<div style="height: 40px"><h5 class="card-title">Album: {{album.album_title}}</h5></div>
<div style="height: 40px"><p class="card-text">Artist: {{album.artist}}</p></div>
<!-- Detail -->
<a href="{% url 'music:detail' album.id %}" class="btn btn-primary btn-sm">View Detail</a>
<!-- Edit -->
<a class="btn btn-default btn-sm" href="{% url 'music:album-update' album.id %}">
<span class="glyphicon glyphicon-pencil"></span>
</a>
<!-- Delete -->
<a class="btn btn-default btn-sm" href="{% url 'music:album-delete' album.id %}">
<span class="glyphicon glyphicon-trash"></span>
</a>
<!-- Favorite -->
<a href="" class="btn btn-default btn-sm btn-favorite">
<span class="glyphicon glyphicon-star {% if album.is_favorite %}active{% endif %}"></span>
</a>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
------------------------------------------
#music/templates/album_confirm_delete
{% extends 'music/base.html' %}
{% block title %}Delete Album{% endblock %}
{% block body %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-7">
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Delete Album</legend>
<h4>Are you sure to delete Album {{album.album_title}}?</h4>
</fieldset>
<div class="form-group">
<button class="btn btn-danger btn-sm" type="submit">Delete</button>
<a class="btn btn-secondary btn-sm" href="{% url 'music:index' %}">Cancel</a>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
--------------------------
#music/views
class AlbumDelete(LoginRequiredMixin, DeleteView):
model = Album
#redirect to home page after delete
success_url = reverse_lazy('music:index')
----------------------
#music/urls
#music/album/id/delete/
path('album/<pk>/delete/', views.AlbumDelete.as_view(), name='album-delete'),
reference:
https://stackoverflow.com/questions/21941503/django-delete-unused-media-files
No comments:
Post a Comment