Home > Net >  Django DeleteView SuccessMessageMixin -- how to pass data to message?
Django DeleteView SuccessMessageMixin -- how to pass data to message?

Time:12-11

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?

CodePudding user response:

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'
  • Related