timothy-knab timothy-knab - 1 month ago 6x
Python Question

How can I use request.form in Flask/Python to get a variable textarea name?

In my HTML template, I've added the following

into a flask for loop:

{% for message in messageList %}
<form action="/comment/{{ message['id'] }}" method='POST' id='createComment{{ message["id"] }}'>
<textarea name='comment{{ message["id"] }}' id='comment{{ message["id"] }}' class='postComment'></textarea>
<button form='createComment{{ message["id"] }}' formaction="/comment/{{ message['id'] }}" formmethod='post' type='submit' class="ui-button ui-corner-all ui-widget createCommentButton">Post a comment</button>
{% endfor %}

Using Flask with Python, I'm trying to grab the value of my dynamically generated

(In the example above, if
id = 38
, name would read as

I'm having trouble properly using request form to get this data, can anyone help?

Here's my Python code below which handles the route:

@app.route('/comment/<id>', methods=["POST"])
def createComment(id):
query = 'INSERT INTO comments (message_id, user_id, comment, created_at, updated_at) VALUES (:message_id, :user_id, :comment, NOW(), NOW());'
data = {
'message_id' : id,
'user_id' : session['loggedInUser'],
'comment' : request.form["comment" & id]
mysql.query_db(query, data)
flash('Comment has been created!')
return redirect('/')

Does anyone know how I should appropriately format
in this scenario, as demonstrated above? Thank you!


Should be request.form["comment" + id]

Better yet, to avoid a key error:

request.form.get("comment" + id, 'oops, bad id')