我正在尝试在用户提交而不选择无线电选项时发出错误,但它无法正常工作。当我渲染这样的字段时:{{ render_field(form.example) }}
它打印(self.gettext('PICK SOMETHING')
,但是当我使用下面的格式时,没有任何事情发生:
{% for subfield in form.religion %}
{{ render_field(subfield, class_="foo") }}
{{ render_field(subfield.label) }}
{% endfor %}
radio.py
class ReligionField(SelectField):
widget = ListWidget(prefix_label=False)
option_widget = RadioInput()
def pre_validate(self, form):
for v, _ in self.choices:
if self.data == v:
break
else:
raise ValueError(self.gettext('PICK SOMETHING'))
class ReligionForm(FlaskForm):
religions = ['Christian', 'Muslim', 'Hindu', 'Buddhist']
choices = [(x.lower(), x.title()) for x in sorted(religions)]
religion = ReligionField('Religion', validators=[DataRequired()], choices=choices, render_kw={"class":"post", "type":"radio"})
@app.route('/',methods=['post','get'])
def hello_world():
form = ReligionForm()
if form.validate_on_submit():
print form.religion.data
else:
print form.errors
return render_template('radio.html', form=form)
如果我提交而未选择任何选项,如何覆盖pre_validate
以引发错误?
答案 0 :(得分:1)
试试这个脚本:
from flask import Flask
from flask import render_template
from flask import request
from flask import flash
from flask import redirect
from flask_wtf import FlaskForm
from wtforms import SelectField
from wtforms.widgets import ListWidget, RadioInput
from wtforms.validators import DataRequired
app = Flask(__name__)
class ReligionField(SelectField):
widget = ListWidget(prefix_label=False)
option_widget = RadioInput()
def pre_validate(self, form):
for v, _ in self.choices:
if self.data == v:
break
else:
raise ValueError(self.gettext('PICK SOMETHING'))
class ReligionForm(FlaskForm):
religions = ['Christian', 'Muslim', 'Hindu', 'Buddhist']
choices = [(x.lower(), x.title()) for x in sorted(religions)]
religion = ReligionField('Religion', validators=[DataRequired()], choices=choices, render_kw={"class":"post", "type":"radio"})
@app.route('/',methods=['GET','POST'])
def hello_world():
form = ReligionForm(request.form)
if request.method == 'POST':
if form.validate_on_submit():
print form.religion.data
else:
print form.religion.errors[0]
flash(form.religion.errors[0])
return redirect('/')
return render_template('radio.html', form=form)
if __name__ == "__main__":
app.run()
radio.html
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<form method="post">
{% for subfield in form.religion %}
<li>{{subfield.label}} {{subfield}} </li>
{% endfor %}
<button>Submit</button>
</form>