Part 5: Django CRUD, Delete

Continued from Part 4: Django CRUD, Create

Full code on https://github.com/shanegibney/djangoCRUD

Next we will delete an instance, or row from the model ‘Members’. First we will place an icon at the end of the row in the table, which we want to delete. Add the following data cell to the table in ‘index.html’,

<td><a href="{% url 'delete_new' item.id %}"><span class="glyphicon glyphicon-trash"></span></a></td>

If you are not using Bootstrap simply replace the span tags with ‘Delete’.

<td><a href="{% url 'delete_new' item.id %}">Delete</a></td>

We can see here that the hyper-link takes us to a url called ‘delete_new’. Also the ‘id’ of the row is passed. We need to create this url in ‘urls.py’ add the following,

url(r'^delete/(?P\d+)/$', home.delete_new, name='delete_new'),

This creates a url for example ‘delete/27’ where 27 is the ‘id’ and this is then passed to the view ‘delete_new’.
Let’s create this view in ‘views.py’. We will need to import ‘get_object_or_404’.

from django.shortcuts import render, get_object_or_404
........
 
def delete_new(request, id):
     post = get_object_or_404(Members, pk=id)
     post.delete()
     return redirect(init)

Here we see that we have passed ‘id’ along with ‘request’. ‘post’ is passed the instance of the ‘Members’ model with pk=id. This object ‘post’ has a method ‘.delete()’, which in the case deletes an instance of the ‘Members’ model. An instance of a class, i.e. ‘Members’ is a row in the database. Next we use ‘redirect’ to go back to the ‘init’ view which renders ‘index.html’.

Now we have an example of the ‘D’ for ‘delete’ in CRUD.

Part 6: Django CRUD, Update