DEV Community

loading...

Show Message in Class-Based Views - Django

serhatteker profile image Serhat Teker Originally published at tech.serhatteker.com on ・2 min read

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:

# 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",
          ],
     },
]
Enter fullscreen mode Exit fullscreen mode

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:

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
Enter fullscreen mode Exit fullscreen mode

Code Example

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

Views

#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"
Enter fullscreen mode Exit fullscreen mode

URL

# urls.py

from django.utils.translation import ugettext_lazy as _

from .views import BookUpdateView


path(_('book/update/'), BookUpdateView.as_view(), name='book-update'),
Enter fullscreen mode Exit fullscreen mode

Template

<!-- 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>
Enter fullscreen mode Exit fullscreen mode

All done!

Discussion (0)

pic
Editor guide