trco / django-bootstrap-modal-forms

A Django plugin for creating AJAX driven forms in Bootstrap modal.
MIT License
384 stars 142 forks source link

Delete view success message is shown although object not deleted #223

Open christianwgd opened 1 year ago

christianwgd commented 1 year ago

If I override the post method of the BSDeleteModal class to handle a ProtectedError (because a foreign key is still pointing to the object that should be deleted), the success message is shown although there's a redirect to another view.

I've made some extensions to the sample app to demonstrate the problem: https://github.com/christianwgd/django-bootstrap-modal-forms/tree/message_error I've added a new object to the model that has a foreign key to a book. To avoid changes to the ui I added an admin for both models.

The only workaround for the problem I found by now was overriding the complete post method, setting the success message from there and set the class property success_message to None.

christianwgd commented 1 year ago

After taking a closer look to the mixins, it seems like the only way to go is this one:

def post(self, request, *args, **kwargs):
    try:
        self.get_object().delete()
        messages.success(self.request, self.success_message)
    except models.ProtectedError:
        messages.error(
            self.request,
            'Cannot delete book due to existing reference'
        )
    return redirect(self.success_url)

If so and there's no better idea it would be fine to have some words on this in the docs and this issue could be closed. Let me know if I shall provide that as a PR.