Show Message in Class-Based Views - Django
Serhat Teker
Posted on March 1, 2021
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",
],
},
]
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
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"
URL
# urls.py
from django.utils.translation import ugettext_lazy as _
from .views import BookUpdateView
path(_('book/update/'), BookUpdateView.as_view(), name='book-update'),
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>
All done!
💖 💪 🙅 🚩
Serhat Teker
Posted on March 1, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.