Django删除错误信息

Dom*_*nik 3 django django-templates django-models django-forms django-views

我有两个型号。当我尝试删除联系人时收到错误

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>]>)
Run Code Online (Sandbox Code Playgroud)

我不想看到 django 错误页面。我要发送信息“该记录无法删除,但该联系人已用于预订”

你能帮助我吗 ?

问候

zai*_*zil 5

delete()您可以在 a 中使用try:except并返回带有自定义错误消息的响应,

from django.db.models import ProtectedError

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