Answer the question
In order to leave comments, you need to log in
Django: how to disable object deletion via admin?
Good afternoon.
After clicking on the delete button in the admin panel, I want to do some kind of "check", if the check is correct, then delete the record, if not, then return to the same page with an error (similar to ValidationError), where the message ala "the record cannot be deleted" is displayed because ...".
There admin.ModelAdmin
is a has_delete_permission method, while I use it, it is responsible for displaying the "delete" button:
def has_delete_permission(self, request, obj=None):
if obj:
a = 1
if a:
return True
return False
def delete_model(self, request, obj):
if True:
obj.delete()
else:
raise Exception
Answer the question
In order to leave comments, you need to log in
in addition, delete_model, like save, cannot be used to block the deletion of an object, only to add actions before and after deletion.
from django.contrib import messages
def delete_model(self, request, obj):
"""Если какая-то проверка успешна - удалить объект, если нет, то показать сообщение об ошибке."""
if check_permission(obj):
return super().delete_model(request, obj)
# При следующем запросе захватываем только ошибки.
# Так после нажатия на кнопку удаления не будет захвачено ложное сообщение
# об успешном удалении.
messages.set_level(request, messages.ERROR)
message = "You cant delete this!"
# Посылаем свое сообщение об ошибке.
self.message_user(request, message, level=messages.ERROR)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question