Search code examples
pythonjsonflaskwerkzeug

Flask - Error werkzeug.exceptions.BadRequestKeyError -


I am trying to run my first flask app, but I am getting the following error after sending the POST request on Postman.

Error: werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'goal'

The error is probably coming from here: goal = request.form['goal'] , I have already tried changing the request.form to request.jsonor form.get without success. :(

Any ideas?

Note: I am using Windows, Visual Studio, Python 3.9 and Postman.


app = Flask(__name__)

@app.route('/create', methods=('GET', 'POST'))

def create():
    if request.method == 'POST':
        goal = request.form['goal']
        content = request.form.get['content']
        
        if not title:
            flash('Goal is required!')
    return calc(goal,content)
    
if __name__ == "__main__":
   app.run(debug=True)

def calc(goal, content):

#rest of the code here...#

    return jsonify({
        "status": 200,
        "message": "Success",
        "data":data
})```

Solution

  • It appears to me that you haven't created your initial base webpage (index.html), which would contain your form element.

    If you look at https://github.com/jmcp/find-my-electorate/blob/master/app.py#L271, you'll see that the base route calls render_template() with an argument, which is https://github.com/jmcp/find-my-electorate/blob/master/templates/index.html. That creates a element which is passed to the POST method.

    In your snippet you don't have anything like that, so there's no request object to pass at all.