Django - How to send a success message using a UpdateView CBV

marcosgue picture marcosgue · Oct 12, 2016 · Viewed 6.9k times · Source

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

This is my view

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 %}

and in the settings i add this

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!

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

Answer

Alasdair picture Alasdair · Oct 12, 2016

To enable the messages in class based views, you need to use the SuccessMessageMixin.

from django.contrib.messages.views import SuccessMessageMixin

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