Show a successful message with Class Based Views

Elio Clímaco Herrera picture Elio Clímaco Herrera · Jul 23, 2014 · Viewed 12.9k times · Source

I, want show a successful message when a row is saved, using Django's messaging framework with Class Based Views, with code shown below, but don't show the message.

Any help would be very much appreciated

#views.py

from django.views.generic import ListView, CreateView, UpdateView, TemplateView
from django.contrib.messages.views import SuccessMessageMixin

class CreateEmployee(SuccessMessageMixin, CreateView):
    model = Employee
    template_name = 'employees/create.html'
    form_class = frmCreate

    def get_success_url(self):
       return reverse('Employees:Create')

    def get_context_data(self, **kwargs):
        contexto = super(CreateEmployee, self).get_context_data(**kwargs)
        contexto['action'] = reverse('Employees:Create')
        return contexto

    success_message = 'Employee successful created'



#template
#create.html

<form action="{{ action }}" method="POST" role="form">
    {% csrf_token %}

    {{ form.as_p }}

    <input type="submit" value="Save" class="btn btn-success">
<form>

{% if messages %}
    <div class="col-lg-3 color03">
        <ul class="messages">
            {% for message in messages %}
                <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
            {% endfor %}
        </ul>
    </div>
{% endif %}

Answer

Alexey picture Alexey · Oct 20, 2017

Just use self.request like this:

from django.contrib import messages
messages.add_message(self.request, messages.INFO, 'Hello world.')