Delete data from database in Django

How to delete data from database in django?

To delete the data, we need to pass the id of the student/record in the url. Our .html file will now be as shown below:

{% extends 'accounts/layouts/maintemp.html' %}

{% block title %}
    All Students
{% endblock title %}

{% block content %}
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <h1>All Students </h1>
                <form action="" method='POST'>
                    {% csrf_token %}
                    <table class="table table-bordered table-striped">
                        {% for x in form %}
                                <td>{{ }}</td>
                                <td>{{ }}</td>
                                <td>{{ }}</td>
                                <td>{{ }}</td>
                                    <a href="{% url 'edit-stud' %}" class="btn btn-primary btn-sm">Edit</a> 
                                    <a href="{% url 'delete-stud' %}" class="btn btn-danger btn-sm">Delete</a>
                        {% endfor %}

{% endblock content %}

So first let us create a url for performing the delete operation. Open the file and add the below path:

    path('delete-students/<str:pk>/', views.deleteStudent, name="delete-stud"),

Now we have to create a function in the file with the name deleteStudent and pass the pk which we have written in the path. Open he file and add the function as shown below:

def deleteStudent(requestpk):
    student_data = Student.objects.get(id=pk)
    return redirect('students')

As you can see the code is very simple, we are just fetching the record of that particular id and then using the delete function to delete that data and redirect to the url with the name 'students'.

There is another method to perform the delete operation i.e. Confirm and delete. In this process we will be rendering a delete.html file in which we will show a message "Are you sure you want to delete this data?" and on clicking the yes button it will come to the same function and inside the function we will write an IF statement to check if the method is POST and then delete it. 

Both the method are demostrated in the above video.

Tags: Funda of web it Django tutorials, Django tutorials, Django tutorials funda, django for beginners, Delete data in django, CRUD applications in django, delete data using id in django, django 3 tutorials

© Copyright - 2018 - 2023 | All rights reserved at Funda of Web IT