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

烈酒焚心 提交于 2020-05-13 04:45:31

问题


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

回答1:


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!!!!'


来源:https://stackoverflow.com/questions/39999956/django-how-to-send-a-success-message-using-a-updateview-cbv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!