Django - 如何使用UpdateView CBV发送成功消息

时间:2016-10-12 13:30:37

标签: django django-class-based-views

(首先抱歉我的英语不好) 我试图在用户保存更改时在UpdateView中显示消息!

这是我的观点

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

保存应用时加载相同的模板!但我喜欢在保存对象时显示引导警报!

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

{% 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'

但是我无法显示消息!对象的更改保存正常,只需要显示消息!

编辑:我在这里显示我的设置,以显示我按照文档中的所有步骤

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',
            ],
        },
    },
]

2 个答案:

答案 0 :(得分:12)

enable the messages in class based views,您需要使用SuccessMessageMixin

from django.contrib.messages.views import SuccessMessageMixin

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

答案 1 :(得分:0)

您还可以像这样覆盖form_valid方法:

from django.contrib import messages
from django.http import HttpResponseRedirect

class NeedUpdateView(UpdateView):
   ...
   def form_valid(self, form):
      messages.success(self.request, "This is my success message")
      super().form_valid(form)
      return HttpResponseRedirect(self.get_success_url())