Flask werkzeug.exceptions.BadRequestKeyError

29,021

When your page is first loaded, there is no request.form dictionary, which is why you get the key error. You need to write an if statement to check if the form was submitted or if the page is being loaded the first time.

from flask import redirect, url_for

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST': 
      data = Info(request.form['name'], request.form['number1'], request.form['number2'])
      db.session.add(data)
      db.session.commit()
      return redirect(url_for('index'))
    else:
      return render_template('index.html')
Share:
29,021

Related videos on Youtube

jpanknin
Author by

jpanknin

Updated on August 06, 2020

Comments

  • jpanknin
    jpanknin about 2 years

    I've tried several different flask apps and get the following error every time.

    werkzeug.exceptions.BadRequestKeyError

    werkzeug.exceptions.HTTPException.wrap..newcls: 400 Bad Request: KeyError: 'name'

    I can't figure out why. It must be something with my setup because the same thing is happening in different applications. I set up a very simple model with minimal code to demonstrate. If I remove the name key I get the same error with the number1 key. And I can't find anything on what this error even means.

    app.py

    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    
    app = Flask(__name__)
    app.config['DEBUG'] = True
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///flow.sqlite3'
    
    db = SQLAlchemy(app)
    
    from routes import *
    
    if __name__ == '__main__':
        # db.drop_all()
        db.create_all()
        app.run()
    

    routes.py

    from flask import render_template, request
    from app import app, db
    from models import Info
    
    @app.route('/', methods=['GET', 'POST'])
    def index():
        data = Info(request.form['name'], request.form['number1'], request.form['number2'])
        db.session.add(data)
        db.session.commit()
        return render_template('index.html', data=data)
    

    models.py

    from app import db
    
    class Info(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(80))
        number1 = db.Column(db.Integer)
        number2 = db.Column(db.Integer)
    
        def __init__(self, name, number1, number2):
            self.name = name
            self.number1 = number1
            self.number2 = number2
    

    index.html

    <!DOCTYPE html>
    <html lang="en" dir="ltr">
      <head>
        <meta charset="utf-8">
        <title></title>
      </head>
      <body>
        <form id='basic' action="index.html" method="post">
          <label for="name">Name:</label>
          <input type="text" name="name" placeholder="Name">
          <label for="number1">Number 1:</label>
          <input type="number" name="number1">
          <label for="number2">Number 2:</label>
          <input type="number" name="number2">
          <button id='btn_submit' type="submit" name="button">Submit</button>
        </form>
      </body>
    </html>
    

Related