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

查看:25
本文介绍了如何使用 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?

推荐答案

根据HTML5 文档,未加引号的属性不能有嵌入空格.

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天全站免登陆