I’m using Django and I want my users to confirm that they really want something to be deleted. I’m considering pure Django solution (no Javascript confirmations).
According to what I think,I can create a new page containing “Yes” and “No” buttons. If user presses “Yes”, my site will go on and delete the object from the database.
Is it the right way to do deletion without using Javascript? How would you implement the feature if you were me?
I’m using Django and I want my users to confirm that they really want
Share
I would use Django’s built in
DeleteView, which will display a confirmation page for an HTTPGETrequest and perform deletion for an HTTPPOSTrequest.The documentation gives this example:
I’d recommend reading the documentation for the
SingleObjectMixinwhich explains how to customise the way the view finds the object to delete (the default is to look for an URL keyword argument calledpk), and for theTemplateResponseMixinwhich explains how to customise the template that is used (the default is'myapp/author_check_delete.html').This is just one of a number of class-based generic views that make basic operations (displaying a page for a single model instance, for a list of model instances, and handling editing, deletion etc.) very quick and easy to implement.
If you wanted to enhance this with JavaScript later you could always write some unobtrusive JS that detects links to the deletion confirmation page (by looking for a class, or a particular URL) and adds a click handler that pops up a confirmation dialog and then sends a
POSTrequest to the URL in the link’shrefattribute. You would also need to modify the view slightly to return a JSON object whenrequest.is_ajax()isTrue, so that your JS would know if the deletion had succeeded or failed, which would probably involve overriding one of the methods inherited from theDeletionMixin.