CBV – DeleteView

From Classy Class Based Views DeleteView

View for deleting an object retrieved with self.getobject(), with a

response rendered by a template.

Attributes

There are no new attributes, but 2 that we’ve seen are required: (1) queryset or model; and (2) success_url

Example

views.py

class myDeleteView(DeleteView):
    queryset = Person.objects.all()
    success_url = reverse_lazy('rango:list_view')

urls.py

path('delete_view/<int:pk>', views.myDeleteView.as_view(), name='delete_view'),

<template_name>.html

Below is just the form that would be needed to get the delete to work.

    <form method="post">
    {% csrf_token %}
    <table border="1">
        <tr>
        <th>First Name</th>
        <th>Last Name</th>
        </tr>
        <tr>
            <td>{{ person.first_name }}</td>
            <td>{{ person.last_name }}</td>
        </tr>
    </table>
    <div>
        <a href="{% url 'rango:list_view' %}">Back</a>
        <input type="submit" value="Delete">
    </div>
    </form>

Diagram

A visual representation of how DeleteView is derived can be seen here:

Conclusion

As far as implementations, the ability to add a form to delete data is about the easiest thing you can do in Django. It requires next to nothing in terms of implementing. We now have step 4 of a CRUD app!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.