Django delete view


Django Delete View

  • Django delete view used to delete a record from the database through user interaction.
  • It identifies the object based on the primary key.

function based delete view

  • Look at the code below
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
from my_app.models import Contact

def fbv_delete_view(request, pk):
    obj = get_object_or_404(Contact, id=pk)
    if request.method.lower() == 'post':
        return HttpResponse('Delete success')
    context = {'object': obj}
    return render(request, 'delete_template.html', context)
  • For GET request, it shows info about the deleted object.
  • Once user confirms the delete with POST request then it deletes the object and returns the response.

class based delete view

  • Django provides the generic view DeleteView to delete object.
  • Look at the code below.
from django.http import HttpResponse
from django.views.generic.edit import DeleteView
from my_app.models import Contact

class CBVDeleteView(DeleteView):
    pk_url_kwarg = 'pk'
    queryset = Contact.objects.all()
    template_name = 'delete_template.html'

    def form_valid(self, form):
        self.object = self.get_object()
        return HttpResponse('Delete success')
  • It works same as the function based delete view implemented above.
  • pk_url_kwarg - to identify the object or the record
  • Attributes queryset or model or method get_object() is required to get the object.

configure urls

  • open my_app/ and add below code to it.
from django.urls import path
from my_app import views

urlpatterns = [
    # ...
    path('fbv_delete_view/<int:pk>', views.fbv_delete_view, name='fbv_delete_view'),
    path('cbv_delete_view/<int:pk>', views.CBVDeleteView.as_view(), name='cbv_delete_view'),
    # ...