[Solved]-PUT and DELETE Django

22👍

According to the HTML standard, the valid methods for form are GET and POST. So you can’t do like this <form method="delete">.
However Django correct handle ‘PUT’ and ‘DELETE’ (and all others) http methods.

from django.views.generic import View


class TestView(View):
    http_method_names = ['get', 'post', 'put', 'delete']

    def put(self, *args, **kwargs):
        print "Hello, i'm %s!" % self.request.method

    def delete(self, *args, **kwargs):
        print "Hello, i'm %s!" % self.request.method


Hello, i'm PUT!
[06/Apr/2016 23:44:51] "PUT /de/teacher/test/ HTTP/1.1"
Hello, i'm DELETE!
[06/Apr/2016 23:57:15] "DELETE /de/teacher/test/ HTTP/1.1"

You can make PUT and DELETE http calls thought the ajax.
If you need to use it form you can do some workaround:

<form action="{% url 'teacher:test' %}" method="post">
    {% csrf_token %}
    <input type="hidden" name="_method" value="delete">
    <input type="submit" value="Delete">
</form>


class TestView(View):
    http_method_names = ['get', 'post', 'put', 'delete']

    def dispatch(self, *args, **kwargs):
        method = self.request.POST.get('_method', '').lower()
        if method == 'put':
            return self.put(*args, **kwargs)
        if method == 'delete':
            return self.delete(*args, **kwargs)
        return super(TestView, self).dispatch(*args, **kwargs)

    def put(self, *args, **kwargs):
        print "Hello, i'm %s!" % self.request.POST.get('_method')

    def delete(self, *args, **kwargs):
        print "Hello, i'm %s!" % self.request.POST.get('_method')


Hello, i'm delete!
[07/Apr/2016 00:10:53] "POST /de/teacher/test/ HTTP/1.1"
Hello, i'm put!
[07/Apr/2016 00:10:31] "POST /de/teacher/test/ HTTP/1.1"

It’s not the real PUT but you can use the same interface for forms and ajax/api calls.

Leave a comment