Dec 31, 2014

How to use request.PUT or request.DELETE in Django

Those of you who use Django might know that using request.PUT or request.DELETE on Django doesn't work. This is because Django doesn't construct dictionaries for such "verbs", and you need to work with request.raw_post_data or request.body and parse it to get your data (Go ahead, give it a try, while I have a cookie!)

If you are creating a simple REST API, you are not going to have a good time unless you are working with a framework.

Wouldn't it be nice if you could use request.PUT just like the dicts request.POST and request.GET After finally searching online, I have stumbled upon a way to do just that.

You can find the code on BitBucket.

    if request.method == "PUT":
        if hasattr(request, '_post'):
            del request._post
            del request._files
            request.method = "POST"
            request.method = "PUT"
        except AttributeError:
            request.META['REQUEST_METHOD'] = 'POST'
            request.META['REQUEST_METHOD'] = 'PUT'
        request.PUT = request.POST

What you do here is simply change the request method back to POST, reload the variables and rename the request method and request.POST dictionary. A nice hack to get your job done.

Liked this post? Have any suggestions? Just let me know. Feel free to comment below!

0 responses:

Post a Comment