Issue
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:
{% 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")
Answered By - A l w a y s S u n n y
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.