Search code examples
djangodjango-viewsdjango-class-based-views

Django DeleteView SuccessMessageMixin -- how to pass data to message?


I am using SuccessMessageMixin on a CreateView and DeleteView.

In the CreateView, I can send the book title to the success_message, like so:

    success_message = "%(title)s added successfully"

Which correctly flashes "Great Expectations added successfully" on the success url.

But in DeleteView, I can't access the title. I can send a generic message saying "book deleted", but I can't send a message saying "Great Expectations has been deleted".

Is there a way that I can pass info about what's being deleted to the success_message?


Solution

  • The reason this does not work is because a DeleteView works with an empty form, so without cleaned data.

    You can override get_success_message and work with:

    from django.contrib.messages.views import SuccessMessageMixin
    from django.views.generic import DeleteView
    
    
    class MyDeleteView(SuccessMessageMixin, DeleteView):
        model = Book
    
        def get_success_message(self, cleaned_data):
            return f'{self.object.title} has been deleted'