Django Admin删除默认保存消息

时间:2018-09-25 16:46:07

标签: django message default

我已在模型管理员中添加了此额外消息,基本上我想删除默认消息。有没有人可以帮助我做到这一点?

我的实际信息:

def save_model(self, request, obj, form, change):
        # add an additional message
        user = request.user
        messages.info(request, "Dear " + str(user)+ " "+ " please note that your parking plot has been reserved")
        super(ParcareModelAdmin, self).save_model(request, obj, form, change)

默认有点烂!

谢谢!

default

2 个答案:

答案 0 :(得分:0)

我解决了以下问题,尽管它不是很优雅,但是可以工作:

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)

答案 1 :(得分:-1)

这不是最优雅的解决方案,但是您始终可以覆盖response_add类的response_changeModelAdmin方法,删除self.message_user调用,如果不这样做,不想让您的admin.py文件上的所有内容混乱,您只需在帮助程序文件中创建SilentModelAdmin,即可覆盖这些方法并删除您不想显示的消息。