英文:
<input> not retrieved using Flask in Python
问题
以下是翻译好的内容:
我正在使用Python创建一个简单的表单。
以下是HTML代码:
<form class="msger-inputarea" action="{{url_for('get_learn')}}" method="post">
<input name="my_msg" id="my_msg" type="text" class="msger-input" placeholder="输入您的消息...">
<button onclick="msg_sent()" type="submit" class="msger-send-btn">发送</button>
</form>
以下是Python Flask代码:
def get_learn():
if request.method == 'POST':
new_question = str(request.form.get("my_msg"))
print(new_question)
return render_template('learn.html')
print(new_question)
打印出 None
看起来 request.form
是一个空字典。
print(request.form)
返回 ImmutableMultiDict([])
它应该包含 my_msg
,这应该是用户输入的内容。
英文:
I am creating a simple form in python.
Here is the HTML:
<form class="msger-inputarea" action="{{url_for('get_learn')}}" method="post">
<input name ="my_msg" id="my_msg" type="text" class="msger-input" placeholder="Enter your message...">
<button onclick="msg_sent()" type="submit" class="msger-send-btn">Send</button>
</form>
And here is the Python Flask code:
def get_learn():
if request.method == 'POST':
new_question = str(request.form.get("my_msg"))
print(new_question)
return render_template('learn.html')
print(new_question)
prints None
It appears that request.form is an empty dict.
print(request.form)
returns ImmutableMultiDict([])
It should be having my_msg, which should be what the user has inputed.
答案1
得分: 1
使用request.values.get(<elem_name>, <default_value>)
来避免担心是POST还是GET,或者是否尝试从表单获取数据。
例如:
request.values.get('my_msg', None)
英文:
To avoid having to worry about whether it's POST or GET or whether you're trying to get the data from a form, use request.values.get(<elem_name>, <default_value>)
i.e.
request.values.get('my_msg', None)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论