Source code for superdjango.db.locked.models

# Imports

from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.timezone import now
from ..audit.utils import is_audit_model

# Exports

__all__ = (
    "LockedModel",
)

# Constants

AUTH_USER_MODEL = settings.AUTH_USER_MODEL

# Models


[docs]class LockedModel(models.Model): """A model that prevents itself from being deleted or updated.""" is_locked = models.NullBooleanField( _("locked"), help_text=_("Indicates this record should not be deleted.") ) locked_by = models.ForeignKey( AUTH_USER_MODEL, blank=True, help_text=_("The user that locked the record."), null=True, on_delete=models.SET_NULL, related_name="%(app_label)s_%(class)s_locked_records", verbose_name=_("locked by") ) locked_dt = models.DateTimeField( _("locked date/time"), blank=True, help_text=_("Date and time the record was locked."), null=True ) class Meta: abstract = True
[docs] def lock_record(self, user, commit=True): """Lock the record. :param user: The user instance. :type user: AUTH_USER_MODEL :param commit: Save after locking. :type commit: bool .. note:: Nothing is done if the record is already locked. """ if self.is_locked: return None self.is_locked = True self.locked_by = user self.locked_dt = now() if is_audit_model(self): # noinspection PyUnresolvedReferences self.audit(user, commit=False) if commit: self.save(update_fields=["is_locked", "locked_by", "locked_dt"])
[docs] def unlock_record(self, user, commit=True): """Unlock the record. :param user: The user instance. :type user: AUTH_USER_MODEL :param commit: Save after unlocking. :type commit: bool .. note:: Nothing is done if the record is already unlocked. """ if not self.locked_dt: return self.is_locked = False self.locked_dt = None if is_audit_model(self): # noinspection PyUnresolvedReferences self.audit(user, commit=False) if commit: self.save(update_fields=["is_locked", "locked_dt"])