保存模型后如何向django管理员显示消息? [英] How to show a message to a django admin after saving a model?

查看:99
本文介绍了保存模型后如何向django管理员显示消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在管理员保存特定模型后向管理员显示一条消息,例如现在启用系列。

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

我可以看到我会怎么做如果这是一个列表操作(message_user),但我看不到如何从CRUD主表单中执行此操作。

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.

有人知道怎么做吗?

谢谢

推荐答案

旧问题,但至少值得我认为一个小例子

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

@Davor Lucic指出了正确的解决方案。
到目前为止,Django附带了一个很酷的消息框架

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

因此,假设您希望在Car模型中的car对象更改所有者时在Django Admin中发出通知,您可以执行以下操作:

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)

值得一提的是,如果要包含H邮件中的TML标签,您必须添加:

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.

这篇关于保存模型后如何向django管理员显示消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆