user5647529
user5647529

Reputation:

How to prevent model instance deletion?

I would like to use a method I could use to prevent an admin from deleting a SingleBook instance if is_available_returned is False. The logic is that the record of a borrowed book should not be deleted until the book is returned. I would prefer a proper manner of handling this instead of throwing an exception. Any help would be appreciated.

class SingleBook(models.Model):
    serial_number = models.CharField(primary_key=True , max_length=150, blank=False)
    book_id = models.ForeignKey(LibraryBook, on_delete=models.CASCADE)
    is_available_returned = models.BooleanField(default=True)

    def __unicode__(self):
        return unicode(self.book_id)

PS:

Django==1.9.8
django-material==0.8.0
django-model-utils==2.5.1
psycopg2==2.6.2
wheel==0.24.0

Upvotes: 0

Views: 1345

Answers (1)

M.Void
M.Void

Reputation: 2894

from django.core.exceptions import ValidationError
from django.db.models.signals import pre_delete
from django.dispatch import receiver

@receiver(pre_delete, sender=SingleBook)
def delete_is_available_returned(sender, instance, **kwargs):
    if instance.is_available_returned:
       raise Exception('This book cant be deleted')

Raising exception in signal should brake delete() method execution while returning exception to the place it was invoked

Upvotes: 2

Related Questions