Django CRUD: The ‘UpdateView’ and ‘DeleteView’

3D isometric visualization of a robot repairing a record and another deleting a record, representing Django UpdateView and DeleteView.

You can Create (Forms) and Read (List/Detail Views) data. Now let’s finish the set with Update and Delete, using Django UpdateView DeleteView for these operations.

Django’s generic views make this incredibly easy.

1. The Update View

This view will automatically find a post, show a form pre-filled with its data, and save the changes.

pages/views.py

from django.views import generic
from django.urls import reverse_lazy
from .models import Post

# ... your other views ...

class PostUpdateView(generic.UpdateView):
    model = Post
    fields = ['title', 'text']
    template_name = 'pages/post_edit.html'
    success_url = reverse_lazy('post_list')

pages/templates/pages/post_edit.html (This template works for both Update and Create!)

<h1>{% if object %}Edit Post{% else %}New Post{% endif %}</h1>
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Save</button>
</form>

Note: UpdateView automatically sends the object (the post) to the template, so we can check if it exists to change the title.

2. The Delete View

This view shows a “Are you sure?” confirmation page and then deletes the object.

pages/views.py

# ...
class PostDeleteView(generic.DeleteView):
    model = Post
    template_name = 'pages/post_delete.html'
    success_url = reverse_lazy('post_list')

pages/templates/pages/post_delete.html

<h1>Delete Post</h1>
<p>Are you sure you want to delete "{{ post.title }}"?</p>
<form method="post">
  {% csrf_token %}
  <button type="submit">Confirm Delete</button>
</form>

3. The URLs

Add these to pages/urls.py:

# ...
from .views import PostListView, PostDetailView, PostUpdateView, PostDeleteView
urlpatterns = [
    path('', PostListView.as_view(), name='post_list'),
    path('post/<int:pk>/', PostDetailView.as_view(), name='post_detail'),
    path('post/<int:pk>/edit/', PostUpdateView.as_view(), name='post_edit'),
    path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post_delete'),
]

Similar Posts

Leave a Reply