Delete record using class based view in django

How to delete record using class based view ?

I am using below view.

class UserDeleteView(DeleteView):
    model = User
    success_url = reverse_lazy('dashboard')
    template_name = 'delete_user_confirm.html'

Is it possible to avoid template_name = 'delete_user_confirm.html' ?

If you don’t want a confirmation page, then why are you using a DeleteView?

From the docs for DeleteView

A view that displays a confirmation page and deletes an existing object.

If you don’t need the confirmation page - if you’re looking to directly delete an object, then you almost certainly don’t need a CBV, and may not even need a separate view for that. (It depends upon the page you’ve created allowing users to select the object(s) to be deleted.)

It is a mistake in Django to think that using CBVs is always the best way to go - it’s not, and especially not to limit yourself to the Django-provided CBVs. Those CBVs have a relatively specific range of intended usage. Not everything you do is going to fit within the patterns they support.

1 Like

Thanks @KenWhitesell . Actually I am using CBV all over the application. That’s why I am looking for solution using CBV.

How can I delete a record without a separate view ?

That’s not the best perspective to have. You want to avoid that trap. (It’s almost as bad as the perspective that “everything I need to do can be done with the admin”.)

You’re better off identifying the functionality of the views, then asking the questions “Is this suitable for a CBV?” and “Is this suitable for a Django-provided CBV?”

It’s architecturally incorrect to work from the assumption that every view you write is best served by a CBV, and even worse to believe that the Django-provided CBVs are the best solution in every case where a CBV is appropriate. That approach can lead to a number of very awkward situations - views that end up being far more complex than they need to be.

I would need to see the view creating the original page - but it is possible that that view could handle the post request for the delete.