Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bad Request received in trying to get Flask form to display

I have a simple Flask form that takes the username but it doesn’t work. I keep getting a Bad Request error. Here’s my code:

This is my main.py:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def index():
    variable = request.form["recipe"]
    return render_template("index.html")

if __name__=='__main__': 
    app.run()

This is my index.html that the form resides in:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{% extends "base.html" %}
{% block content %}
    <h1>Cooking By Myself</h1>
    <form action="/" method="POST">
        <h3>Add Recipe</h3>
        <p>
            <label for="recipe">Name:</label>
            <input type="text" name="recipe"/>
        </p>
        <p><input type="submit" name="submit_recipe"/></p>
    </form>
{% endblock %}

And this is my base.html file:

<!DOCTYPE html>
<html>
  <body>
    {% block content %}
    {% endblock %}
  </body>
</html>

I don’t know where I’m going wrong?

>Solution :

The issue in your code lies in the index function(main.py) of your Flask application. You’re trying to access the request.form attribute without checking if the request method is a POST request. This causes a Bad Request error when the page is initially loaded because the form data is not available in the request.form dictionary initially.

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        recipe = request.form.get("recipe")
        # Process the recipe data as needed
        print(f"Recipe: {recipe}")
    return render_template("index.html")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading