Django-如何使用UpdateView CBV发送成功消息 [英] Django - How to send a success message using a UpdateView CBV

查看:66
本文介绍了Django-如何使用UpdateView CBV发送成功消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(首先对不起我的英语不好)
当用户保存更改时,我试图在UpdateView中显示一条消息!

(first of all sorry for my bad english) I'm trying to show a message in a UpdateView when the users save the changes!

这是我的观点

class NeedUpdateView(UpdateView):
    model = Need
    template_name = 'purchases/needs_update_form.html'
    pk_url_kwarg = 'need_id'
    success_message = 'List successfully saved!!!!'
    fields = [
        'detail',
    ]

在保存应用程序时,将加载相同的模板!但是如果保存对象,我想显示引导警报!

When you save the app loads the same template! but i like to show a bootstrap alert if save the object!

这是模板中的代码,用于显示消息

This is code in the template to show the message

{% if messages %}
<div class="alert alert-success">
    {% for m in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ m }}</li>
    {% endfor %}
</div>
{% endif %}

,然后在设置中我添加

MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'

但是我无法显示消息!

But the i can't show the messages! The changes in the object are saving fine only need to show the message!

编辑:我在这里显示我的设置以表明我遵循文档中的所有步骤

i show here my settings to show that i follow all the steps in the docs

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

DJANGO_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.i18n',
                'apps.cart.context_processors.cart',
            ],
        },
    },
]


推荐答案

在基于类的视图中启用消息,您需要使用 SuccessMessageMixin

from django.contrib.messages.views import SuccessMessageMixin

class NeedUpdateView(SuccessMessageMixin, UpdateView):
    ...
    success_message = 'List successfully saved!!!!'

这篇关于Django-如何使用UpdateView CBV发送成功消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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