[Django]-Custom error message in Django admin actions

53👍

The message_user function used within the admin simply uses the contrib.messages package. You could try something like this:

from django.contrib import messages

# Then, when you need to error the user:
messages.error(request, "The message")

You can also use warning, debug, info and success in place of error

Hope that helps!

51👍

from django.contrib import messages
...
self.message_user(request, "The message", level=messages.ERROR)

Сan also be used (messages.ERROR, messages.WARNING, messages.DEBUG, messages.INFO, messages.SUCCESS)

5👍

You can use django.contrib.messages backend

from django.contrib import messages

def my_action(self, request, queryset):
  #do something
  messages.error(request,'Error message')

This will show the error message and the red error sign.

3👍

Not sure whether this was fixed in newer django versions (I found the behaviour you described in django 1.2.1 and also in django-grappelli 2.0), but if you use Bartek’s method above, you’d also probably want to change the admin templates to show the messages differently. Specifically in base.html:

Change this:

{% if messages %}
        <ul class="messagelist">{% for message in messages %}<li>{{ message }}</li>{% endfor %}</ul>
    {% endif %}

to this:

{% if messages %}
        <ul class="messagelist">{% for message in messages %}<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message}}</li>{% endfor %}</ul>
    {% endif %}

You might still need to tweak some CSS on top of that too, but at least it would come up as a different li class on the HTML.

Here’s a sample CSS change (compatible with grappelli)

ul.messagelist li.error {
background: url('../img/icons/icon-no.png') 20px 50% no-repeat;
background-color: #f2e6e6;

}

Leave a comment