A
A
Alexey Ochkasov2021-02-20 09:39:51
HTML
Alexey Ochkasov, 2021-02-20 09:39:51

How to fix error in flask request.form?

Hello. i have this code:

<label>
    <textarea name="recipe" rows="15" cols="55"></textarea>
</label>
<form action="/save" method="POST">
    <input type="submit" value="Сохранить">
</form>

from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
    return render_template("create.html")
@app.route('/save', methods=['POST', 'GET'])
def do_save():
    if request.method == 'POST':
        recipe = request.form['recipe']
        print(recipe)
    else:
        print("GET")
    return render_template('index.html')

When I click Save , I get the error werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'recipe' . If done , then print returns None. Please tell me what is the problem? Why can't Flask get the recipe key even though the HTML code has it and I'm putting information into it? recipe = request.form.get('recipe')

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Yakushenko, 2021-02-20
@DeD0k_CtaT1cT

Because your text field is not attached to the form, add a idpointer to the form to the form and to the text field:

<label>
    <textarea name="recipe" rows="15" cols="55" form="some-form"></textarea>
</label>
<form id="some-form" action="/save" method="POST">
    <input type="submit" value="Сохранить">
</form>

D
Dr. Bacon, 2021-02-20
@bacon

Because the recipe should be inside the form tag, it's worth brushing up your knowledge of html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question