# Imports
from django.contrib import admin
# Models
[docs]class BaseLockedModelAdmin(admin.ModelAdmin):
"""Add support for :py:class:`superdjango.db.locked.models.LockedModel`.
Inspired by this `SO question on disabling the delete link in the admin`_.
.. _SO question on disabling the delete link in the admin: http://stackoverflow.com/q/4043843/241720
"""
[docs] def get_list_display(self, request):
"""Add lock fields to the display. Override this to add your own fields
or to remove these fields from the list.
"""
a = super().get_list_display(request)
a.append("is_locked")
a.append("locked_by")
a.append("locked_dt")
return a
[docs] def get_fields(self, request, obj=None):
"""Add lock fields to the form. Override this to add your own fields
or to remove these fields from the form.
"""
a = super().get_fields(request, obj)
a.append("is_locked")
return a
[docs] def has_delete_permission(self, request, obj=None):
"""A record that is locked will suspend delete permission."""
if obj.is_locked:
return False
else:
return True
[docs] def has_change_permission(self, request, obj=None):
"""A record that is locked will suspend update permission.
.. note::
Super users always have the ability to change (and therefore lock/unlock) a record.
"""
if request.user.is_superuser:
return True
if obj.is_locked:
return False
else:
return True
[docs] def save_model(self, request, obj, form, change):
"""Override to act on ``is_locked`` field.
- If ``True``, ``lock_record()`` is called.
- If ``False``, ``unlock_record()`` is called.
- If ``None``, no action is taken.
"""
if obj.is_locked:
obj.lock_record(request.user, commit=False)
elif obj.is_locked is False:
obj.unlock_record(request.user, commit=False)
else:
pass
return super().save_model(request, obj, form, change)