pythonhtmlformsflask

Form causes an unsupported media format error


I'm working on a todo app for a class project and the /add_todo route returns a 415 error code whenever I try to add a todo.

@app.route("/add-todo", methods=["GET", "POST"])
def add_todo():
  title = request.get_json().get("title")
  db.session.add(Todo(title=title))
  db.session.commit()
  return '', 204
<form action="/add-todo" method="post" hx-boost="true">
  <input type="text" id="todo_bar">
  <button id="submit">Add</button>
</form>

I've tried everything from changing what the route returns to adding the methods array when declaring the route, yet nothing seems to make a difference.


Solution

  • The data you're sending is form-encoded (by the browser). You can retrieve it by using form instead of get_json:

    @app.route("/add-todo", methods=["POST"])
    def add_todo():
      title = request.form.get("title")
      # Here ---------^
      db.session.add(Todo(title=title))
      db.session.commit()
      return '', 204