Home > OS >  Deleting object in Django
Deleting object in Django

Time:03-29

What is the best practice to delete object in Django? Using simple "a tag" with the link to the view like this:

def deleteStudent(request,id):
    student = get_object_or_404(Student, id = id)
    student.delete()
    return redirect('/')

or using post method:

<form method="POST">
    {% csrf_token %}
    Are you want to delete this item ?
    <input type="submit" value="Yes" />
    <a href="/">Cancel </a>
</form>

and in views:

def deleteStudent(request, id):
    student = get_object_or_404(Student, id = id)

    if request.method =="POST":
        student.delete()
        return redirect('/')
 
    return render(request, "delete_view.html")

I saw in courses that people use both of the methods (it's example code, I'didn't test it or secure views). So if we can delete objects with "POST" method, can I say in the job interview that "POST method can be also used to delete objects"? Thanks for all answers.

CodePudding user response:

The former violates the HTTP standard. As the standard on safe methods of the HTTP specifications [w3.org] says:

In particular, the convention has been established that the GET and HEAD methods SHOULD NOT have the significance of taking an action other than retrieval. These methods ought to be considered "safe".

You thus can not let a GET request remove an item: scrapers like a Google bot might accidentally trigger this view, and thus remove data.

If you want to remove items, usually you do this by a DELETE request, or a POST request. This is also how the DeleteView [Django-doc] is implemented: it will remove the object for a DELETE or POST request. The idea is that for a GET request, you can render a template for example that asks if you are sure you want to remove that item, and thus then make a POST (or DELETE) request when the user confirms.

Often the view will also check if the user is authorized to do so: for example if only the "owner" of an object is allowed to remove such item, then the view should validate this.

I saw in courses that people use both of the methods.

The first one is not a good idea, and violates the HTTP standards. Any course that uses this introduces security risks.

  • Related