How to prevent “Changed successfully” message when overriding save_model method

你离开我真会死。 提交于 2020-08-01 06:13:07

问题


I'm trying to let users view records in the admin but not save anything. So I'm trying to do something like this:

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'.")

This works however I get two messages on the next screen:

My message above first And then a "The ... was changed successfully."

How can I prevent the second message?


回答1:


You can hide certain messages and show others. In your case, you are interested in not displaying the the success message. You can do the following:

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



回答2:


For anyone who needs to eliminate the automatic Django success message in a more flexible way than proposed by the accepted answer, you can do the following:

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!")



回答3:


If you want to prevent success message in case of failure message then you must have to set the error level of the messages.

Something like this ->

    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()

It will avoid coming two messages (Success and Failure) at the same time because we have suppressed success message by changing the error level.




回答4:


Just override def message_user(...) method, do it as follows:

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


来源:https://stackoverflow.com/questions/25449233/how-to-prevent-changed-successfully-message-when-overriding-save-model-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!