Add delete_selected action

This commit is contained in:
Peter Inglesby 2013-05-22 11:07:54 +01:00
parent 8b6b56a1a8
commit 79e6dfad83
2 changed files with 83 additions and 0 deletions

60
djadmin2/actions.py Normal file
View file

@ -0,0 +1,60 @@
from django.core.exceptions import PermissionDenied
from django.template.response import TemplateResponse
from django.utils.text import capfirst
from django.contrib import messages
def get_description(action):
if hasattr(action, 'description'):
return action.description
else:
return capfirst(action.__name__.replace('_', ' '))
def delete_selected(request, queryset):
# We check whether the user has permission to delete the objects in the
# queryset.
#
# TODO: This duplicates some of the permission-checking functionality in
# BaseAdmin2. Investigate how to DRY this out.
#
# TODO: Check that user has permission to delete all related obejcts. See
# `get_deleted_objects` in contrib.admin.util for how this is currently
# done. (Hint: I think we can do better.)
model = queryset.model
opts = model._meta
permission_name = '%s.delete.%s' \
% (opts.app_label, opts.object_name.lower())
has_permission = request.user.has_perm(permission_name)
if len(queryset) == 1:
objects_name = opts.verbose_name
else:
objects_name = opts.verbose_name_plural
if request.POST.get('confirmed'):
# The user has confirmed that they want to delete the objects.
if has_permission:
queryset.delete()
message = "Successfully deleted %d %s" % \
(len(queryset), objects_name)
messages.add_message(request, messages.INFO, message)
return None
else:
raise PermissionDenied
else:
# The user has not confirmed that they want to delete the objects, so
# render a template asking for their confirmation.
if has_permission:
template = 'admin2/bootstrap/delete_selected_confirmation.html'
context = {
'queryset': queryset,
'objects_name': objects_name
}
return TemplateResponse(request, template, context)
else:
message = "Permission to delete %s denied" % objects_name
messages.add_message(request, messages.INFO, message)
return None
delete_selected.description = "Delete selected items"

View file

@ -0,0 +1,23 @@
{% extends "admin2/bootstrap/base.html" %}
{% block content %}
<p>Are you sure you want to delete the selected {{ objects_name }}?</p>
<ul>
{% for item in queryset %}
<li>{{ item }}</li>
{% endfor %}
</ul>
<form method="post">
{% csrf_token %}
<input type="hidden" name="confirmed" value="yes" />
<input type="hidden" name="action" value="delete_selected" />
{% for item in queryset %}
<input type="hidden" name="selected_model_id" value="{{ item.id }}" />
{% endfor %}
<input type="submit"/>
</form>
{% endblock content %}