Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add hard delete action #151

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 80 additions & 1 deletion safedelete/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from django.utils.translation import ugettext_lazy as _

from .utils import related_objects
from .models import HARD_DELETE

# Django 3.0 compatibility
try:
Expand Down Expand Up @@ -48,11 +49,12 @@ class SafeDeleteAdmin(admin.ModelAdmin):
... list_filter = ("last_name",) + SafeDeleteAdmin.list_filter
"""
undelete_selected_confirmation_template = "safedelete/undelete_selected_confirmation.html"
hard_delete_confirmation_template = "safedelete/hard_delete_confirmation.html"

list_display = ('deleted',)
list_filter = ('deleted',)
exclude = ('deleted',)
actions = ('undelete_selected',)
actions = ('undelete_selected', 'hard_delete')

class Meta:
abstract = True
Expand Down Expand Up @@ -165,3 +167,80 @@ def undelete_selected(self, request, queryset):
context,
)
undelete_selected.short_description = _("Undelete selected %(verbose_name_plural)s.")

def hard_delete(self, request, queryset):
""" Admin action to hard delete objects. """
if not self.has_delete_permission(request):
raise PermissionDenied

original_queryset = queryset.all()
undeleted_queryset = queryset.filter(deleted__isnull=True)
queryset = queryset.filter(deleted__isnull=False)

if request.POST.get('post'):
requested = original_queryset.count()
changed = queryset.count()

if changed:
for obj in queryset:
obj.delete(force_policy=HARD_DELETE)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be better to call the base QuerySet delete to delete in bulk, otherwise it could be very long.

if requested > changed:
self.message_user(
request,
"Successfully hard deleted %(count_changed)d of the "
"%(count_requested)d selected %(items)s." % {
"count_requested": requested,
"count_changed": changed,
"items": model_ngettext(self.opts, requested)
},
messages.WARNING,
)
else:
self.message_user(
request,
"Successfully hard deleted %(count)d %(items)s." % {
"count": changed,
"items": model_ngettext(self.opts, requested)
},
messages.SUCCESS,
)
else:
self.message_user(
request,
"No permission for hard delete. Execute soft delete first.",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would change this to something more explicit such as: "You need to soft delete first in order to hard delete an object."

messages.ERROR
)
return None

opts = self.model._meta
if len(original_queryset) == 1:
objects_name = force_text(opts.verbose_name)
else:
objects_name = force_text(opts.verbose_name_plural)
title = "Are you sure?"

deletable_objects, model_count, perms_needed, protected = self.get_deleted_objects(queryset, request)

context = {
'title': title,
'objects_name': objects_name,
'queryset': original_queryset,
'deletable_queryset': queryset,
'undeleted_queryset': undeleted_queryset,
'opts': opts,
'app_label': opts.app_label,
'action_checkbox_name': admin.helpers.ACTION_CHECKBOX_NAME,
'model_count': dict(model_count).items(),
'deletable_objects': [deletable_objects],
'perms_lacking': perms_needed,
'protected': protected,
'media': self.media,
}

return TemplateResponse(
request,
self.hard_delete_confirmation_template,
context,
)

hard_delete.short_description = "Hard delete selected %(verbose_name_plural)s."
31 changes: 31 additions & 0 deletions safedelete/templates/safedelete/hard_delete_confirmation.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{% extends "admin/delete_selected_confirmation.html" %}
{% load i18n l10n %}

{% block object-tools %}{% endblock %}

{% block content %}
<div id="content-main">
<p>{% blocktrans %}Are you sure you want to hard delete the selected {{ objects_name }}?{% endblocktrans %}</p>
{% include "admin/includes/object_delete_summary.html" %}
<form action="" method="post">{% csrf_token %}
<div>
{% for obj in queryset %}
<input type="hidden" name="{{ action_checkbox_name }}" value="{{ obj.pk|unlocalize }}" />
{% endfor %}

<h2>{% translate "Objects" %}</h2>
{% for deletable_object in deletable_objects %}
<ul>{{ deletable_object|unordered_list }}</ul>
{% endfor %}

<p>{% blocktrans %}The following {{ objects_name }} are not soft deleted yet and cannot be hard deleted. {% endblocktrans %}</p>
<ul>{{ undeleted_queryset|unordered_list }}</ul>

<input type="hidden" name="action" value="hard_delete" />
<input type="hidden" name="post" value="yes" />
<input type="submit" value="{% trans "Yes, I'm sure" %}" />
<a href="#" class="button cancel-link">{% translate "No, take me back" %}</a>
</div>
</form>
</div>
{% endblock %}
20 changes: 20 additions & 0 deletions safedelete/tests/test_admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,3 +122,23 @@ def test_admin_undelete_action(self):
pk=self.categories[1].pk
)
self.assertFalse(category.deleted)

def test_admin_hard_delete_action(self):
"""Test objects are hard deleted and action is logged."""
resp = self.client.post('/admin/safedelete/category/', data={
'index': 0,
'action': ['hard_delete'],
'_selected_action': [self.categories[1].pk],
})
self.assertTemplateUsed(resp, 'safedelete/hard_delete_confirmation.html')
self.assertTrue(self.categories[1].deleted)

resp = self.client.post('/admin/safedelete/category/', data={
'index': 0,
'action': ['hard_delete'],
'post': True,
'_selected_action': [self.categories[1].pk],
})

with self.assertRaises(Category.DoesNotExist):
Category.objects.get(pk=self.categories[1].pk)