Kurt Peek
Kurt Peek

Reputation: 57761

Django's SuccessMessageMixin not working with DeleteView

Following https://docs.djangoproject.com/en/2.0/ref/contrib/messages/#adding-messages-in-class-based-views, I'm trying to add a success message to a DeleteView:

from django.views.generic import DeleteView
from django.contrib.messages.views import SuccessMessageMixin


class SessionDelete(SuccessMessageMixin, DeleteView):
    model = Session
    success_url = reverse_lazy('dashboard:sessions')
    success_message = "Session %(id)s (%(session_type)s) was deleted successfully"

However, I've noticed this doesn't work in Django 1.11.9. I found this pull request, https://github.com/django/django/pull/5992, but it appears to have been closed due to inactivity. Do I understand correctly that success messages still don't work correctly with DeleteViews?

Upvotes: 1

Views: 1722

Answers (1)

Mojtaba Arezoomand
Mojtaba Arezoomand

Reputation: 2380

  1. Import from django.contrib import messages

  2. Use this as your view or transform it into a mixin.

class SessionDelete(DeleteView):
    model = Session
    success_url = reverse_lazy('dashboard:sessions')
    success_message = "Session %(id)s (%(session_type)s) was deleted successfully"
    
    def delete(self, request, *args, **kwargs):
        messages.success(self.request, self.success_message, 'danger')

        return super(SessionDelete, self).delete(request, *args, **kwargs)
  1. You don't need the SuccessMessageMixin it is working fine now!

Upvotes: 1

Related Questions