[英]Flask, SQL, HTML: How to use a variable as a key for INSERT statement
I have a site where users post messages to a wall and reply to messages in comment threads. 我有一个站点,用户可以将消息发布到墙上并在评论主题中回复消息。 I can't figure out how to associate comments to messages when the comment form is submitted so that the correct message_id (foreign key) is inserted into the comments table in the database.
我无法弄清楚在提交评论表单时如何将评论与消息相关联,以便将正确的message_id(外键)插入数据库的评论表中。
I am displaying messages and comments from the database with a for loop in my html, and after each message/comment group there is a form that routes to '/post_comment': 我在HTML中用for循环显示来自数据库的消息和注释,并且在每个消息/注释组之后,有一种形式可以路由到'/ post_comment':
{% for message in messages %}
<div>
<h3>{{ message['first_name'] }} {{ message['last_name'] }}</h3>
<h3>{{ message['created_at'] }}</h3>
<p>{{ message['message'] }}</p>
{% for comment in comments %}
{% if message['message_id'] == comment['message_id'] %}
<p>{{ comment['comment'] }}</p>
{% endif %}
{% endfor %}
<form class="comments" action="/post_comment" method="POST">
<h4>Reply</h4>
<textarea id="post_comment" type="textarea" name="comment"></textarea>
<input class="submit" type="submit" value="Post">
</form>
</div>
{% endfor %}
and the /post_comment route looks like this: / post_comment路由如下所示:
@app.route('/post_comment', methods=['POST'])
def post_comment():
query = "INSERT INTO comments (user_id, message_id, comment, created_at, updated_at) VALUES (:user_id, :message_id, :comment, NOW(), NOW())"
data = {
'user_id': session['id'],
'message_id': 10, <<<<<<<<<<<<<<<<<<<<<<<<<<<< WHAT GOES HERE?
'comment': request.form['comment']
}
mysql.query_db(query, data)
return redirect('/wall')
This all works perfectly fine but as you can see, in the /post_comment route I temporarily hard-coded "message_id' as an integer (10), so every comment is being recorded as a reply to message_id 10. What it actually needs to do is pick up the message_id of the preceding message when its associated comment form is submitted. 所有这些工作都很好,但是如您所见,在/ post_comment路由中,我将“ message_id”临时硬编码为整数(10),因此每个注释都被记录为对message_id 10的答复。提交相关消息的评论表单后,选择上一条消息的message_id。
How do I let the form know which message it belongs to, and then how do I pass that information on to my query in my route? 如何让表单知道它属于哪条消息,然后如何将该信息传递给我的路线中的查询?
It's better if you set message_id as auto increment. 最好将message_id设置为自动增量。
If you can't, get the last ID using MAX and then increase it by 1. It's not the cleanest, but it works. 如果不能,请使用MAX获取最后一个ID,然后将其增加1。这不是最干净的,但是可以使用。
SELECT MAX(message_id) AS last_message_id FROM comments;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.