success_message in DeleteView not shown

Magda picture Magda · Jul 18, 2014 · Viewed 7.8k times · Source

I have a DeleteView:

class LectureDelete(SuccessMessageMixin, DeleteView):
model = Lecture
success_message = "Die Veranstaltung wurde gelöscht"
success_url = '/'

def get_object(self):
    qs = super(LectureDelete, self).get_object()
    if self.request.user.has_perm('edit_lecture', qs):
        return qs
    else:
        raise exceptions.PermissionDenied

And in my template to which the success_url links, I have the following code, which works fine with other messages:

{% if messages %}
        {% for message in messages %}
        <p class="alert alert-dismissable {% if message.tags %}alert-{{ message.tags }}"{% endif %}>
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
            {{ message }}
        </p>
        {% endfor %}
    {% endif %}

But the message is not shown. Am I missing something? What am I doing worng? Thanks!

Answer

Heyl1 picture Heyl1 · Aug 15, 2014

I think this issue in the Django issue tracker should answer your question.

SuccessMessageMixin hooks to form_valid which is not present on DeleteView to push its message to the user.

It also gives an alternative way which works for me:

from django.views.generic.edit import DeleteView
from django.core.urlresolvers import reverse_lazy
from django.contrib import messages
from .models import Thing

class ThingDelete(DeleteView):
    model = Thing
    success_url = reverse_lazy('list')
    success_message = "Thing was deleted successfully."

    def delete(self, request, *args, **kwargs):
        messages.success(self.request, self.success_message)
        return super(ThingDelete, self).delete(request, *args, **kwargs)

SuccessMessageMixin was not used in the delete-view (but I do use it for the Create and Update views). Hopefully this will be improved in later versions of Django (see issue for more info).