How to prevent the message "Changed successfully" when overriding the save_model method

I am trying to allow users to view entries in the administrator, but not save anything. So I am 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 following screen:

My first message is above And then "... was successfully changed."

How to prevent a second message?

+9
source share
3 answers

You can hide certain messages and show others. In your case, you are interested in not showing a 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 ..') 
+13
source

For anyone who needs to eliminate the automatic Django success message in a more flexible way than the proposed 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!") 
+2
source

If you want to prevent a success message from reporting an error, you need 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() 

This will prevent the two messages from appearing simultaneously (Success and Failure), since we suppressed the success message by changing the error level.

0
source

Source: https://habr.com/ru/post/974217/


All Articles