Delete a data from Database in Django

To delete a record in the database, we must use the delete() method. Removing items is easier than changing items, because the method is the same for a queryset as for the instances of models.

Django Model Overview Example

We will be doing the following in this Django ModelForm Example

  • Create a Page for entry of Details(Name, Email-id, Password) and save it into the database(which will be done automatically by model forms).
  • Create the details page where we would view the student entries in an ordered list, save and update the data.

Since we have already created the Form in our previous article, we will continue with that. In case in any doubt refer to our previous article.

Running the app

  • On the running the admin panel we can see the following data present in our database:

So, to delete a data we need to use delete() command on the specific ID and make the following changes in the views.py:

from django.shortcuts import render

# Create your views here.
from .forms import StudentRegistration
from .models import User
def showformdata(request):
    if request.method == 'POST':
        fm = StudentRegistration(request.POST)
        if fm.is_valid():
            nm = fm.cleaned_data['name']
            em = fm.cleaned_data['email']
            pw = fm.cleaned_data['password']
            reg = User(id=1)
            reg.delete()

    else:
        fm = StudentRegistration()
    return render(request,'enroll/userregistration.html',{'form':fm})

Let’s try to submit the following data:

Now, let’s check the database and see whether it is deleted or not.

Since, we have used ID=1 in our code, so the details of ID 1 have been deleted and although we saved another details it is deleted from the database.