<input> 在 Python 中未使用 Flask 检索到

huangapple go评论71阅读模式
英文:

<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:

&lt;form class=&quot;msger-inputarea&quot; action=&quot;{{url_for(&#39;get_learn&#39;)}}&quot; method=&quot;post&quot;&gt;
&lt;input name =&quot;my_msg&quot; id=&quot;my_msg&quot; type=&quot;text&quot; class=&quot;msger-input&quot; placeholder=&quot;Enter your message...&quot;&gt;
&lt;button onclick=&quot;msg_sent()&quot; type=&quot;submit&quot; class=&quot;msger-send-btn&quot;&gt;Send&lt;/button&gt;
&lt;/form&gt;

And here is the Python Flask code:

def get_learn():
    if request.method == &#39;POST&#39;:
        new_question = str(request.form.get(&quot;my_msg&quot;))
        print(new_question)

        return render_template(&#39;learn.html&#39;)

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(&lt;elem_name&gt;, &lt;default_value&gt;)

i.e.

request.values.get(&#39;my_msg&#39;, None)

huangapple
  • 本文由 发表于 2023年7月3日 22:36:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76605765.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定