I am trying to send data from Python / Flask to an HTML form textarea but need some help.
responses.html
is shown below.
{% extends "layout.html" %} {% block title %} Responses {% endblock %} {% block main %} <form action="/responses" method="post"> <div class="mb-3"> <label for="response">Enter response here:</label><br> <input class="form-control mx-auto w-auto" autocomplete="off" id="response" name="response" placeholder="Enter your response here" type="textarea"> </div> <button class="btn btn-primary" type="submit">Submit</button> </form> {% endblock %}
A portion of app.py
is shown below:
@app.route("/responses", methods=["GET", "POST"]) @login_required def responses(): """Continue student application""" if request.method == "GET": user_id = session["user_id"] # check for existing data to supply the template. responses = db.execute( "select * from extended_responses where user_id = ?", user_id) return render_template("responses.html", responses) # User reached route via POST if request.method == "POST": user_id = session["user_id"] # get form data response = request.form.get("response") # check if this is an update or new entry responses = db.execute( "select * from extended_responses where user_id = ?", user_id) if len(responses) > 0: # update answers db.execute("update extended_responses set user_id = ?, response = ? where user_id = ?", user_id, response, user_id) else: # insert answers db.execute("INSERT INTO extended_responses (user_id, response) VALUES (?, ?)", user_id, response)
I would like to display any previously recorded responses in the response textarea
of responses.html
while preserving the placeholder when no previous response was received from the user.
Advertisement
Answer
I suggest you replace input
tag with textarea
tag. Then you can add responses in textarea like this (p.s. you need to format responses, this example will just display SQL result):
<form action="/responses" method="post"> <div class="mb-3"> <label for="response">Enter response here:</label><br> <textarea class="form-control mx-auto w-auto" autocomplete="off" id="response" name="response" placeholder="Enter your response here" >{{responses}}</textarea> </div> <button class="btn btn-primary" type="submit">Submit</button> </form>
If you still want to use input
tag (although input type='textarea'
is not valid HTML tag, you should switch to type='text'
) then you should add value
attribute, like this:
<input ... type="text" value="{{responses}}"/>
Both approaches will populate the input/textarea with responses if there is any response, otherwise, it will show a placeholder
Also, I’ve noticed that you have an error in SQL code, you always replace the answer with the newest one so you’ll have just one answer in DB.