user1102171
user1102171

Reputation: 684

method="delete" from html form in FLASK

I have an HTML form:

{% set delete_urls = url_for('store_add') ~ store_id ~ "?__METHOD_OVERRIDE__=DELETE" %}
<form action="{{delete_urls}}" name="delete" method="post" id="{{form_id}}" style="display:none">

and in the views:

class StoreAdd(MethodView):

    @login_required
    def delete(self,store_id):
        store_selected = request.args['store_id']

        qstr = "DELETE FROM store WHERE store_id=%d AND cust_id=%d"%(store_id,self.cust_id)
        h = pgexec(qstr,False,True)
        h.process()

        flash("deleted the store:%d"%(store_selected))
        return redirect(url_for('store_add'))

store_add = StoreAdd.as_view('store_add')
app.add_url_rule('/storeadd/',
                 defaults={'store_id': 0},
                 view_func=store_add,
                 methods=["GET","PUT"])
app.add_url_rule('/storeadd/',
                 view_func=store_add,
                 methods=["POST"])
app.add_url_rule('/storeadd/<int:store_id>',
                 view_func=store_add,
                 methods=['DELETE','PUT','GET'])

Of course implemented the routing:

from werkzeug import url_decode
from flask import flash

class MethodRewriteMiddleware(object):

    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        if 'METHOD_OVERRIDE' in environ.get('QUERY_STRING', ''):
            args = url_decode(environ['QUERY_STRING'])
            method = args.get('__METHOD_OVERRIDE__')
            if method in ['GET', 'POST', 'PUT', 'DELETE']:
                method = method.encode('ascii', 'replace')
            environ['REQUEST_METHOD'] = method
        return self.app(environ, start_response)

But still on submission of the delete form it cannot access the delete method? What is going wrong?

Edit:

The problem with delete is as follows. When I submit the form it seems it tries to "POST" to url:

/storeadd/13?__METHOD_OVERRIDE__=DELETE

But the POST url rule says it can only be: /storeadd. Thus it gives 405 ERROR Page. Thus the override which should happen never happens.

Upvotes: 2

Views: 2616

Answers (1)

Yinian Chin
Yinian Chin

Reputation: 98

Have you applied this middleware on your flask application?

app.wsgi_app = MethodRewriteMiddleware(app.wsgi_app)

Upvotes: 1

Related Questions