问题
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>
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>
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?
回答1:
According to the HTML5 documentation, an unquoted attribute must not have an embedded space.
Your input
element expands to the following text:
<input type = 'radio' name= 'categories' 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.
Try quoting the value
attribute value:
<li><input type = 'radio' name= 'categories' value ="{{cat}}">{{cat}}</li>
来源:https://stackoverflow.com/questions/48572024/how-to-carry-string-with-spaces-through-a-html-form-using-flask