Delete records in Django

In any CRUD system, the delete or delete operation allows you to delete a record or a set of records from the database; This is one of the easiest operations to perform but also the most risky, since it is an operation that cannot be reversed; once the registry is deleted there is no going back and the registry cannot be recovered therefore, it is usually an operation that is limited either by privileges, or by adding warning dialogs among other types of solutions; for now, for those of us who are interested in performing the operation and that's it, without worrying about implementing additional logic to avoid this type of operation:

As part of our CRUD, we have the elimination phase, which consists of two fundamental steps:

Get reference to the element that we want to delete through the ORM.
Delete the same.

def delete(request, pk):
   product = get_object_or_404(Product, id=pk)
   product.delete()
   return redirect('gestion:index')

For the rest, once deleted you can generally do a couple of things, here we do a redirect, but if, for example, this function is consumed by JavaScript, you can return a json with a response to be parsed.

Finally, the reference to the above function:

<a href="{% url 'gestion:delete' p.id %}">Borrar</a>

- Andrés Cruz

En español
Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.