E
E
exctac2018-01-31 13:45:02
Django
exctac, 2018-01-31 13:45:02

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.ModelAdminis 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

But this is not exactly what I need, I want the button to always be there, and the permission to delete or not was after it was pressed. Form validation works exactly like this.
You can also do this:
def delete_model(self, request, obj):
        if True:
            obj.delete()
        else:
            raise Exception

But, in this way, it simply throws out the error page, and not the page for editing the record with an error, besides, delete_model, like save, cannot be used to block the deletion of an object, only to add actions before and after deletion.
Thanks for participating!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
javedimka, 2018-01-31
@exctac

in addition, delete_model, like save, cannot be used to block the deletion of an object, only to add actions before and after deletion.

This is absolutely not true. The model will be deleted if super().delete_model(request, obj) is explicitly called when overriding this method, otherwise not.
You can make it so that the messages framework does not capture the standard message about successful deletion that is sent by the admin from the intermediate page and add your own:
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)

Well, still do something with logging, because "deletion" will still fall into the "recent actions" on the main page of the admin panel, even though the object has not been deleted.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question