Sandro Munda
Sandro Munda

Reputation: 41078

Django form PUT and DELETE http method

I'm using Django Tastypie in order to have a Rest API. It works well.

Now, I would like to use my Rest API in a django form. I know web browsers can't send a PUT or a DELETE http method (only GET and POST).

For example, to solve the problem with ExpressJS (A NodeJS web framework) :

<input type="hidden" name="_method" value="delete"/>

I can use this hack.

Is it a way to do the same thing using Django Form ?

Upvotes: 4

Views: 2773

Answers (2)

Jayson
Jayson

Reputation: 702

TastyPie supports this internally using the X-Http-Method-Override header, but that it doesn't sound like headers are any more accessible that method overrides. On the off chance that you can do this, see here.

Your best bet is probably to use a Django middleware like this:

METHODS = [ 'GET', 'PUT', 'POST', 'DELETE' ]

class DjangoMethodMiddleware(object):
    def process_request(self, request):
        meth = request.REQUEST.get('_method', None)
        if meth is None:
            return
        if meth in METHODS:
            request.method = meth
        else:
            pass # TODO: logging?

Stash this in a middleware.py in your site, then you'll then need to load this middleware in your Django settings. Magic!

Upvotes: 2

sarveshseri
sarveshseri

Reputation: 13985

I think you can send Put or delete using javascript like this

$("your_form_id").submit(function(e){
    $.ajax({
        url: 'your url',
        type: "PUT",
        data: $("your_form_id").serialize(),
        cache: false,
        dataType: "text",
        success: function(data){
            do_something()
        },
        error: function() {
            console.log("ERROR");
        }
    });
});

Or even this hack method of your's will work.... you will have to check for this value on server side and then call he rest API accordingly.

Upvotes: 1

Related Questions