Show Message in Class-Based Views - Django
Tags: django, python, middleware
Published: 2021-03-01 15:04:48

---
title: Show Message in Class-Based Views - Django
published: true
date: 2020-11-27 00:00:00 UTC
tags: django, python, middleware
canonical_url: https://tech.serhatteker.com/post/2020-11/show-success-message-in-cbv-django/
---

You want to add *message* after a *user* `submit` a django form: `POST`, `CREATE/UPDATE/DELETE` methods.

## Prerequisites

You must have below configurations in your settings to show messages in **Django**:

```python
# settings.py

INSTALLED_APPS = [
    "django.contrib.messages",
]

MIDDLEWARE = [
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
]

TEMPLATES = [
    {
        "OPTIONS": {
            "context_processors": [
                "django.contrib.messages.context_processors.messages",
          ],
     },
]
```

## Add Message

You can update your own methods or classes to add messages, however it is better to use what **Django** provides already: `SuccessMessageMixin`.

[SuccessMessageMixin] adds a success message attribute to `FormView` based classes:

```python
from django.contrib import messages


class SuccessMessageMixin:
    """
    Add a success message on successful form submission.
    """
    success_message = ''

    def form_valid(self, form):
        response = super().form_valid(form)
        success_message = self.get_success_message(form.cleaned_data)
        if success_message:
            messages.success(self.request, success_message)
        return response

    def get_success_message(self, cleaned_data):
        return self.success_message % cleaned_data
```

## Code Example

As an instance I will show `views`, `urls` and `template`:

### Views

```python
#views.py

from django.contrib.messages.views import SuccessMessageMixin
from django.urls import reverse_lazy
from django.views.generic.edit import UpdateView

from .forms import BookCreateForm


class BookUpdateView(SuccessMessageMixin, UpdateView):
    """
    List all Book objects, update a Book object in database and add a success
    message into template.
    """
    model = Book
    form_class = BookUpdateForm
    success_url = reverse_lazy('books:book-update')
    template_name = 'books/update.html'
    success_message = "%(book)s was updated successfully"
```

### URL

```python
# urls.py

from django.utils.translation import ugettext_lazy as _

from .views import BookUpdateView


path(_('book/update/'), BookUpdateView.as_view(), name='book-update'),
```

### Template

```jinja
<!-- templates/books/update.html -->

 {% if messages %}
     {% for message in messages %}
         <div class="text-center alert alert-{{ message.tags }}">
             {{ message|safe }}
         </div>
     {% endfor %}
 {% endif %}

<form method="POST">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form>
```


All done!




[Adding messages in class-based views]: https://docs.djangoproject.com/en/3.1/ref/contrib/messages/#adding-messages-in-class-based-views
[SuccessMessageMixin]: https://github.com/django/django/blob/master/django/contrib/messages/views.py