如何使用Flask通过HTML表单携带带空格的字符串 [英] how to carry string with spaces through a HTML form, using Flask

查看:75
本文介绍了如何使用Flask通过HTML表单携带带空格的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Flask和Python 3.6构建一个简单的在线测验,使用带有单选按钮的HTML表单在Flask路线之间传递选定的答案.第一步是在进入实际测验页面之前,为测验选择一个类别,如下所示:

I'm trying to build a simple online quiz using Flask and Python 3.6, using HTML forms with radio buttons to carry the selected answers between Flask routes. The first step is to select a category for the quiz, before leading to the actual quiz page, as follows:

app = Flask(__name__)
categories = ['Europe', 'South America', 'North America']
@app.route('/')
def select():
    return render_template('selecting.html', cats= categories)

@app.route('/quiz', methods = ['POST'])
def quizing():
    selected_cat = request.form['categories']
    return "<h1>You have selected category: " + selected_cat + "</h1>

其中"selecting.html"如下:

Where 'selecting.html' is as follows:

<form action='/quiz' method='POST'>
<ol>
{% for cat in cats%}
    <li><input type = 'radio' name= 'categories' value ={{cat}}>{{cat}}</li>
{% endfor %}
</ol>
<input type="submit" value="submit"/>
</form>

当我选择欧洲"时,测验页面显示为:

When I select 'Europe', the quiz page reads:

<h1>You have selected category: Europe</h1>

但是,当我选择北美"时,测验页面显示为:

However, when I select 'North America' the quiz page reads:

<h1>You have selected category: North</h1>

为什么Flask路线之间没有包含所选类别的第二个单词,我该怎么做才能保留完整的类别名称?

Why is the second word of the selected category not carried between the Flask routes and what can I do to retain the full category name?

推荐答案

根据

According to the HTML5 documentation, an unquoted attribute must not have an embedded space.

您的 input 元素扩展为以下文本:

Your input element expands to the following text:

<input type = 'radio' name= 'categories' value =North America>

尽管您的意思是说它具有一个 value 属性,其值是 North America ,但实际上它具有一个 value 属性,并带有一个 North 的值和具有空值的 America 属性.

Even though you mean for it to have a value attribute with a value of North America, it actually has a value attribute with a value of North and a America attribute with an empty value.

尝试引用 value 属性值:

<li><input type = 'radio' name= 'categories' value ="{{cat}}">{{cat}}</li>

这篇关于如何使用Flask通过HTML表单携带带空格的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆