[Django]-Django delete error message

5👍

You could use delete() in a try:except and return a response with a custom error message,

from django.db.models import ProtectedError

try:
    instance.delete()
except ProtectedError:
    error_message = "This object can't be deleted!!"
    return JsonResponse(error_message)

2👍

Hi you need to use exception ProtectedError

try:
    #DELETE STUFF
except ProtectedError:
    #CUSTOM MESSAGE

Raised to prevent deletion of referenced objects when using
django.db.models.PROTECT. models.ProtectedError is a subclass of
IntegrityError.

doc here : https://docs.djangoproject.com/fr/1.11/ref/exceptions/#django.db.models.ProtectedError

Leave a comment