如何呈现Flask WTF HTML 5小部件? [英] How render a Flask WTF HTML 5 widget?
问题描述
我正在尝试使用Flask的html 5小部件来构建 RangeInput(搜索范围"以找到它).我认为我在HTML模板中缺少某些内容,因为它的呈现方式如下:
I'm trying to use the html 5 widgets of Flask to build a RangeInput (search for "range" to find it). I think I'm missing something in the HTML template because it renders like that:
如您所见,这不是我想要的:我期待这样的事情:
As you can see, it's not what I wanted: I was expecting something like that:
因此,我认为错误不是那么棘手,但我找不到它.这是我的不同文件:
So I think the error isn't that tricky but I cannot find it. Here are my different files:
__author__ = 'laurentmeyer'
# That's my main class, don't be afraid, all is local, you cannot hack anything
from MySQL import MySQL
from flask import Flask, render_template
from Form import Form;
mysql = MySQL();
app = Flask(__name__)
app.config['MYSQL_DATABASE_USER'] = 'Laurent'
app.config['MYSQL_DATABASE_PASSWORD'] = 'laurent'
app.config['MYSQL_DATABASE_DB'] = 'Houses'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
@app.route("/")
def home():
cursor = mysql.connect().cursor()
cursor.execute("SELECT * from Offers;")
data = cursor.fetchall()
form = Form(csrf_enabled=False);
if data is None:
return "No data"
else:
return render_template('DB template.html',form = form, offers = data)
if __name__ == "__main__":
app.run()
我的HTML模板:
<!DOCTYPE html>
<html>
<head>
<title>Tableau des maisons</title>
</head>
<body>
<form><p>Test: {{ form.ImportanceOfPrice }} </p></form>
<!--<table>{% for house in offers %}<tr><td>Titre: {{house[0]}}</td><td>Lien: <a href="{{house[1]}}">{{house[1]}}</a></td></tr>{% endfor %}</table>-->
</body>
</html>
最后,这是我的Form.py(非常简单):
Finally, here is my Form.py (very simple):
__author__ = 'laurentmeyer'
from flask_wtf import Form
from flask_wtf.html5 import RangeInput
class Test(Form):
ImportanceOfPrice = RangeInput(0.1)
推荐答案
以下代码应该很有用:
from flask import Flask, render_template
from wtforms import Form
from wtforms.fields.html5 import DecimalRangeField
app = Flask(__name__)
app.config['DEBUG'] = True
class TestForm(Form):
price_importance = DecimalRangeField('Price Importance')
@app.route("/")
def home():
form = TestForm(csrf_enabled=False)
return render_template('tpl.html', form=form)
if __name__ == "__main__":
app.run()
模板tpl.html,默认情况下必须将其放置在模板"文件夹中:
Template tpl.html, which, by default, must be placed into a folder 'templates':
<!DOCTYPE html>
<html>
<body>
<form>
<p>{{ form.price_importance.label }}: {{ form.price_importance }}</p>
</form>
</body>
</html>
您的代码包含一些错误:
Your code contains some errors:
- Python不需要分号来终止语句.
- 您没有导入正确的表单类(应该导入 Test 表单类)
- 在表单类中,通常应声明 fields (通过小部件呈现)
- Python does not require semi-colons to terminate statements.
- You don't import the right form class (you should import the Test form class)
- In a form class, you should usually declare fields (which are rendered via widgets)
这篇关于如何呈现Flask WTF HTML 5小部件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!