Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django delete error message

i have two models. when i try delete contact recevied error

Exception Value:    

("Cannot delete some instances of model 'GuestContact' because they are referenced through a protected foreign key: 'Reservation.res_company'", <QuerySet [<Reservation: Reservation object>, <Reservation: Reservation object>]>)

i dont' want see django error page. i want send information " this record can't be delete, but this contact is used in reservation"

can you help me ?

regards

like image 204
Dominik Avatar asked Sep 26 '26 23:09

Dominik


2 Answers

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)
like image 107
zaidfazil Avatar answered Sep 29 '26 14:09

zaidfazil


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

like image 21
MaximeK Avatar answered Sep 29 '26 14:09

MaximeK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!