Django admin: Using messages.error still results in confirmation being shown

828 Views Asked by At

I've overridden my save_model() function to wrap the obj.save() call in a try/catch.

def save_model(self, request, obj, form, change):
    from concurrency.exceptions import RecordModifiedError
    from django.http import HttpResponse
    try: 

        obj.save()
        # some other stuff

    except RecordModifiedError:
        messages.error(request, "[!] Record modified. Please try again.")
        #self.message_user(request, "[!] Record modified. Please try again.", level="error")

Catching the RecordModifiedError is working, and the data is not saved. However, the confirmation message that appears on a successful save is still showing, as is the error. I have two contradictory messages being shown!

I'm wondering how to prevent the success message from being displayed. Thanks!

EDIT: also tried the self.message_user() function, but it didn't block the success message either.

3

There are 3 best solutions below

1
On

doesnot it have to be in this way?

try: 

    obj.save()
    messages.error(request, "[!] Record modified.")

except RecordModifiedError:
    messages.error(request, "[!] Record NOT modified. Please try again.")
0
On

I think this should work:

storage = messages.get_messages(request)
storage.used = True
messages.error(request, "[!] Record modified. Please try again.")
0
On

I solved this same issue by overwriting the message_user function. I set a flag if there was an error. If the flag is set, then have message_user return, if not set then call the base class message_user using the super function.