In this article, we are going to see how we can delete multiple rows from our table in Django. To implement this feature we are going to use an HTML table to show our data and we add a checkbox for all rows to select and delete the row.
So first start the setup of your project on click once your setup is completed let's start with code -
Once the setup is completed we have to create a route.
yourappname/urls.py
from django.urls import path from . import views urlpatterns = [ path("grid",views.grid,name="grid"), path("delete_multiple",views.delete_multiple,name="delete_multiple"), ]
After creating the route, we have to write code to load data and show it in the HTML table for that we have to first write code in our views.py
yourappname/views.py
def grid(request):
product = Products.objects.all()
return render(request,"grid.html",{"products":product}) Now create a template to display our data and create a checkbox to select all the rows -
templates/grid.html
<!doctype html>Now we have to write code for deletion based on the selected row.
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Grid</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" >
</head>
<body>
<div class="container">
<form method="post" action="{% url 'delete_multiple' %}">
{% csrf_token %}
<button type="submit" class="btn btn-danger"> Delete All </button>
<table class="table mt-2">
<thead class="bg-dark text-white">
<tr>
<th><input type="checkbox" id="select_all">Select All</th>
<th>Id</th>
<th>Name</th>
<th>Sku</th>
<th>Image</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for product in products %}
<tr>
<td><input type="checkbox" name="selected_item" value="{{ product.id }}"></td>
<td>{{ product.id }}</td>
<td>{{ product.name}}</td>
<td>{{ product.sku}}</td>
<td>{{ product.image}}</td>
<td>
<a href="">Edit</a>
<a href="">Delete</a>
</td>
</tr>
{% endif %}
</tbody>
</table>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$("#select_all").click(function () {
$('input[name="selected_item"]').not(this).prop('checked', this.checked);
});
</script>
</body>
</html>
yourappname/views.py
def delete_multiple(request):
if request.method == 'POST':
record_ids = request.POST.getlist('selected_item')
YourModel.objects.filter(id__in=record_ids).delete()
messages.success(request, 'Selected records have been deleted successfully.')
return redirect('grid')

Comments
Post a Comment