重写save_model方法时如何防止“已成功更改”消息

时间:2014-08-22 14:22:00

标签: django django-admin

我试图让用户在管理员中查看记录但不保存任何内容。所以我试图做这样的事情:

def save_model(self, request, obj, form, change):
    """Override save method so no one can save"""
    messages.error(request, "No Changes are permitted from this screen."
        " To edit projects visit the 'Projects' table, and make sure you are"
        " in the group 'Visitor_Program_Managers'.")

这可行但是我在下一个屏幕上收到两条消息:

我的信息首先在上面 然后一个" ...已成功更改。"

如何阻止第二条消息?

4 个答案:

答案 0 :(得分:12)

您可以隐藏某些消息并显示其他消息。在您的情况下,您有兴趣不显示成功消息。您可以执行以下操作:

def save_model(self, request, obj, form, change):
    messages.set_level(request, messages.ERROR)
    messages.error(request, 'No changes are permitted ..')

答案 1 :(得分:2)

对于需要以比接受的答案提议的更灵活的方式消除自动Django成功消息的任何人,您可以执行以下操作:

from django.contrib import messages, admin

class ExampleAdmin(admin.ModelAdmin):
    def message_user(self, *args):
        pass

    def save_model(self, request, obj, form, change):
        super(ExampleAdmin, self).save_model(request, obj, form, change)
        if obj.status == "OK":
            messages.success(request, "OK!")
        elif obj.status == "NO":
            messages.error(request, "REALLY NOT OK!")

答案 2 :(得分:0)

如果要在出现失败消息时阻止成功消息,则必须设置消息的错误级别。

类似这样的东西->

    if already_exist:
        messages.set_level(request, messages.ERROR)
        messages.error(request, 'a and b mapping already exist. Please delete the current entry if you want to override')
    else:
        obj.save()

这将避免同时出现两个消息(成功和失败),因为我们通过更改错误级别抑制了成功消息。

答案 3 :(得分:0)

只需重写def message_user(...)方法,就可以这样做:

def message_user(self, request, message, level=messages.INFO, extra_tags='',
                 fail_silently=False):
    pass

def save_model(self, request, obj, form, change):
    messages.success(request, 'Write your overrided message here...')
    pass