Search code examples
pythonflaskpostgetjinja2

Can GET a method but POST doesn't work. Any ideas why the method POST isn't uses?


from flask import Flask, render_template, url_for, request, redirect

app = Flask(__name__)

@app.route('/doborpompy', methods=['GET', 'POST'])
def doborpompy():

    if request.method == 'GET':
        return render_template('doborpompy.html')
    else:
        metry = 200
        if 'metry' in request.form:
            metry = request.form['metry']

        return render_template('doborpompy_wynik.html', metry=metry)

"GET /doborpompy%20method=?metry=44&metry_ogrzewane=44&ilosc_osob=44&typ_domu=pasywny&dofinansowanie=dofinansowanie&budget=standard&zrodlo=ogrzewanie_podlogowe&powietrze_woda=woda HTTP/1.1" 404 -

I can go for an option GET, but when I am trying to POST it still trying to do an GET option. Any ideas?


Solution

  • You are not handling the POST Action. By default when you access the route, you are doing a GET Request, so you should handle the POST Like This:

    from flask import Flask, render_template, url_for, request, redirect
    
    app = Flask(__name__)
    
    @app.route('/doborpompy', methods=['GET', 'POST'])
    def doborpompy():
    
        if request.method == "POST":
            return "<h1>This is how to handle post action in the if statement</h1>"
            # rest of your code ...
        
        return render_template("doborpompy.html")
    
    if __name__ == "__main__":
        app.run()
    

    enter image description here

    And you should also edit this line in your doborpompy.html file:

    <form id="formularz_doboru" action="{{url_for("doborpompy")}}" method="POST">

    to

    <form id="formularz_doboru" action="{{url_for('doborpompy')}}" method="POST">