Reputation: 57
I want to show an info message after deleting an object from a database. I decided to use SuccessMessageMixin for that purpose. How I can add object attributes to the success_message?
class PostDeleteView(SuccessMessageMixin, DeleteView):
model = Post
success_url = reverse_lazy('post_list')
def get_success_message(self, cleaned_data):
return 'The ' + str(self.object) + ' post was deleted'
I thought I can do it that way. But there is no message after the deletion.
Upvotes: 1
Views: 885
Reputation: 477685
The SuccessMessageMixin
[Django-doc] only runs when a form is valid, so when the view inherits from a FormView
[Django-doc], or as specified in the documentation:
Adds a success message attribute to
FormView
based classes.
You can not use this with a DeleteView
, since a DeleteView
does not use a FormView
(or uses a FormMixin
).
You can however make your own mixin, and use this for all DeleteView
s based on the implementation of the SuccessMessageMixin
[GitHub]:
from django.contrib import messages
class SuccessDeleteMessageMixin:
success_message = ''
def delete(self, *args, **kwargs):
response = super().delete(*args, **kwargs)
success_message = self.get_success_message()
if success_message:
messages.success(self.request, success_message)
return response
def get_success_message(self):
return self.success_message
and then use this mixin with:
class PostDeleteView(SuccessDeleteMessageMixin, DeleteView):
model = Post
success_url = reverse_lazy('post_list')
def get_success_message(self, cleaned_data):
return f'The post {self.object} was deleted'
Upvotes: 3