0

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
  • Did you try use `pre_delete` of the Django Signals? – M.Void Aug 05 '16 at 18:48
  • pre_delete lets one add some functionality but which functionality would i add to prevent deletion? –  Aug 05 '16 at 19:39
  • 1
    Possible duplicate of [Prevent delete in Django model](http://stackoverflow.com/questions/4825815/prevent-delete-in-django-model) – solarissmoke Aug 06 '16 at 11:35

1 Answers1

2
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

M.Void
  • 2,764
  • 2
  • 29
  • 44