[Django]-Django Admin Remove default save message

0πŸ‘

I solved this problem as follow, although it’s not very elegant but it work:

from django.contrib import messages
from django.contrib import admin

# Register your models here.
from . import models


class RemoveAdminDefaultMessageMixin:

    def remove_default_message(self, request):
        storage = messages.get_messages(request)
        try:
            del storage._queued_messages[-1]
        except KeyError:
            pass
        return True

    def response_add(self, request, obj, post_url_continue=None):
        """override"""
        response = super().response_add(request, obj, post_url_continue)
        self.remove_default_message(request)
        return response

    def response_change(self, request, obj):
        """override"""
        response = super().response_change(request, obj)
        self.remove_default_message(request)
        return response

    def response_delete(self, request, obj_display, obj_id):
        """override"""
        response = super().response_delete(request, obj_display, obj_id)
        self.remove_default_message(request)
        return response


class MessageAdmin(RemoveAdminDefaultMessageMixin, admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        self.message_user(request, 'save success!')
        return super().save_model(request, obj, form, change)


admin.site.register(models.Message, MessageAdmin)
πŸ‘€Angel Liang

0πŸ‘

With messages.set_level(), you can remove the default message then set your custom message separately and differently for adding or changing an object as shown below:

def save_model(self, request, obj, form, change): # Here
    last_part_of_path = request.path.split('/')[-2]

    if last_part_of_path == "add":
        obj.save()
        
        messages.set_level(request, messages.SUCCESS)
        messages.success(request, "Successfully added!!")

    if last_part_of_path == "change":
        obj.save()

        messages.set_level(request, messages.SUCCESS)
        messages.success(request, "Successfully changed!!")

-1πŸ‘

Not the most elegant solution, but you can always override the response_add and response_change methods of the ModelAdmin class, removing the self.message_user calls, and if you don’t want all that clutter on your admin.py file, you can just create a SilentModelAdmin in a helper file where you override those methods and remove the messages you don’t want to be shown.

Leave a comment