Я очень доволен этим удалением:
def price_unit_delete(request, pk):
pu = PriceUnit.objects.get(pk=pk)
template = 'includes/modal/modal_form.html'
if request.POST:
pu.delete()
template = 'dashboard_staff/settings/includes/priceunits.html'
ctx = {'action': reverse("dashboard_staff:settings_delete_priceunit", args=(pu.pk, )),
'title': 'do you really want to delete me ?',
'form': PriceUnitDeleteForm(),
'priceunits': PriceUnit.objects.all()}
return TemplateResponse(request, template, ctx)
Когда элемент ссылается где-либо еще как внешний ключ, он завершается ошибкой. Я думал поймать эту ошибку целостности (во-первых, вызванную psycopg2, а во-вторых, самим django.db), используя блок try
.
Действительно, вы можете сделать в консоли Python:
# in case of ```o``` being referenced somewhere else, returns False
def delete(o):
try:
o.delete()
except:
return False
Я наивно подумал включить в представление такой блок, как этот:
if request.POST:
try:
pu.delete()
except:
return JsonResponse({'data': _(
"You can't delete this object as it is used somewhere else."
)}, status=400)
Но в этом случае исключение не ловится. Я также написал это представление как CBV, оно не может поймать исключение.
Я пробовал этот код в другом проекте, и он работает.
Почему это не работает в случае исключения целостности? и как я мог это отладить?
Вот трассировка исключения, которое я хочу поймать:
File "/home/emilio/.virtualenvs/rdt_2.0/lib/python3.7/site-packages/django/db/backends/base/base.py", line 240, in _commit
return self.connection.commit()
psycopg2.IntegrityError: update or delete on table "prices_priceunit" violates foreign key constraint "prices_prestationtyp_default_price_unit_i_c6ec94f9_fk_prices_pr" on table "prices_prestationtype"
DETAIL: Key (id)=(1) is still referenced from table "prices_prestationtype".
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/emilio/.virtualenvs/rdt_2.0/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/emilio/.virtualenvs/rdt_2.0/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/emilio/.virtualenvs/rdt_2.0/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.7/contextlib.py", line 74, in inner
return func(*args, **kwds)
File "/home/emilio/.virtualenvs/rdt_2.0/lib/python3.7/site-packages/django/db/transaction.py", line 240, in __exit__
connection.commit()
File "/home/emilio/.virtualenvs/rdt_2.0/lib/python3.7/site-packages/django/db/backends/base/base.py", line 262, in commit
self._commit()
File "/home/emilio/.virtualenvs/rdt_2.0/lib/python3.7/site-packages/django/db/backends/base/base.py", line 240, in _commit
return self.connection.commit()
File "/home/emilio/.virtualenvs/rdt_2.0/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/emilio/.virtualenvs/rdt_2.0/lib/python3.7/site-packages/django/db/backends/base/base.py", line 240, in _commit
return self.connection.commit()
django.db.utils.IntegrityError: update or delete on table "prices_priceunit" violates foreign key constraint "prices_prestationtyp_default_price_unit_i_c6ec94f9_fk_prices_pr" on table "prices_prestationtype"
DETAIL: Key (id)=(1) is still referenced from table "prices_prestationtype".