猿问

WTForms:如何为 HTML5 小部件设置默认值?

我正在尝试使用 WTForms 颜色输入字段。


如何#ff0000为输入字段设置默认值(例如 )?


这就是我定义表单的方式:


from wtforms.widgets.html5 import ColorInput


class ColoursForm(Form):

   background_color = StringField(widget=ColorInput())

这是观点:


@app.route("/colours/<token>/", methods=['GET', 'POST'])

def edit_colours(token):

   form = ColoursForm(request.form)

   if request.method == 'GET':

      return render_template('colours_edit.html', form=form, token=token)

   else:  # Request = post

      return redirect(url_for('view_scoreboard', token=token))

在我的 Jinja2 模板 (colours_edit.html) 中,我这样做:


<p> {{ form.background_color() }} Pick a color here </p>

一切正常,但我不知道如何设置默认值。什么不起作用是这样的形式:


background_color = StringField(widget=ColorInput(), default="#ff00ff")


翻过高山走不出你
浏览 222回答 1
1回答

沧海一幻觉

一种方法是检查然后在您的视图中设置数据值。请注意获取表单后的两条新行:@app.route("/colours/<token>/", methods=['GET', 'POST'])def edit_colours(token):&nbsp; &nbsp;form = ColoursForm(request.form)&nbsp; &nbsp;if not form.background_color.data:&nbsp; &nbsp; &nbsp; &nbsp;form.background_color.data = "#ff00ff"&nbsp; &nbsp;if request.method == 'GET':&nbsp; &nbsp; &nbsp; &nbsp;return render_template('colours_edit.html', form=form, token=token)&nbsp; &nbsp;else:&nbsp; # Request = post&nbsp; &nbsp; &nbsp; &nbsp;return redirect(url_for('view_scoreboard', token=token))没有默认值:默认值#ff00ff:这是一个最小的例子,供任何想尝试的人使用:from flask import Flask, request, render_templatefrom wtforms.widgets.html5 import ColorInputfrom wtforms import Form, StringFieldclass ColoursForm(Form):&nbsp; &nbsp; background_color = StringField(widget=ColorInput())app = Flask(__name__)@app.route("/")def edit_colours():&nbsp; &nbsp; form = ColoursForm()&nbsp; &nbsp; if not form.background_color.data:&nbsp; &nbsp; &nbsp; &nbsp; form.background_color.data = "#ff00ff"&nbsp; &nbsp; if request.method == "GET":&nbsp; &nbsp; &nbsp; &nbsp; return render_template("colors_edit.html", form=form)colors_edit.html和OP一样(一定要放在templates文件夹里):<p> {{ form.background_color() }} Pick a color here </p>&nbsp;&nbsp;我不知道为什么您第一次尝试设置默认值不起作用。也没有为我工作。似乎应该如此。这个答案更深入一点。
随时随地看视频慕课网APP

相关分类

Python
我要回答