Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show a message to a django admin after saving a model?

I want to display a message to admins after they save a particular model, something like "Now enable the series".

I can see how I'd do this if it were a list action (message_user) but I can't see how to do this from the main CRUD form.

Does anyone know how?

Thanks

like image 251
Roger Avatar asked Sep 14 '10 20:09

Roger


People also ask

How do I send a message in Django?

To add a message, call: from django. contrib import messages messages. add_message(request, messages.INFO, 'Hello world.

How do I get to the admin page in Django?

To login to the site, open the /admin URL (e.g. http://127.0.0.1:8000/admin ) and enter your new superuser userid and password credentials (you'll be redirected to the login page, and then back to the /admin URL after you've entered your details).

How do I change the admin text in Django?

To change the admin site header text, login page, and the HTML title tag of our bookstore's instead, add the following code in urls.py . The site_header changes the Django administration text which appears on the login page and the admin site. The site_title changes the text added to the <title> of every admin page.


1 Answers

Old question, but worth at least a small example as I think this is quite a common issue.

@Davor Lucic pointed to the right solution. As of today, Django ships with a cool message framework that helps a lot with this.

So, say you want to give notice within the Django Admin whenever a car object within your Car model changes owner, you could do something like that:

admin.py

from django.contrib import admin from django.contrib import messages  from .models import Car   @admin.register(Car) class CarAdmin(admin.ModelAdmin):     list_display = ('owner', 'color', 'status', 'max_speed', )      def save_model(self, request, obj, form, change):         if 'owner' in form.changed_data:             messages.add_message(request, messages.INFO, 'Car has been sold')         super(CarAdmin, self).save_model(request, obj, form, change) 

It's worth mentioning that if you want to include HTML tags in your message, you have to add:

from django.utils.safestring import mark_safe 

which allows you to do something like:

messages.add_message(request, messages.INFO, mark_safe("Please see <a href='/destination'>here</a> for further details")) 

No need to say you'd better be sure the code you're adding is REALLY safe.

Nothing exceptional, but maybe (and hopefully) someone will find it useful.

like image 92
Seether Avatar answered Oct 23 '22 23:10

Seether