Django Delete Record

Django Delete Record

Deleting Records

To delete a record we do not need a new template, but we need to make some changes to the members template.

Of course, you can chose how you want to add a delete button, but in this example, we will add a “delete” link for each record in a new table column.

The “delete” link will also contain the ID of each record.


Modify Template

Add a “delete” column in the members template:

members/templates/index.html:

The result will look like this:


URLs

The “delete” link in the HTML table points to 127.0.0.1:8000/members/delete/ so we will add a path() function in the members/urls.py file, that points the url to the right location, with the ID as a parameter:

members/urls.py:


Code for Deleting Records

Now we need to add a new view called delete in the members/views.py file:

members/views.py:

The delete view does the following:

  • Gets the id as an argument.
  • Uses the id to locate the correct record in the Members table.
  • Deletes that record.
  • Redirects the user back to the index view.

Click on the “delete” link for Jane Doe, and see the result:


ArmenianEnglish