如何忽略flask-wtf中的字段验证? [英] How can I ignore a field validation in flask-wtf?
问题描述
我有一个将项目添加到数据库的表单,该表单包含两个按钮: Cancel
和 Submit
.我遇到的问题是,当我用空白表格按下 Cancel
按钮时,我得到一个请填写此字段.
错误,而不是返回我的主页(请参阅 views.py
了解逻辑).那么,当我按下 Cancel
按钮时,如何让我的应用程序忽略 DataRequired
验证器?
I have a form to add an item to my database, which includes two buttons: Cancel
and Submit
. The problem I have is that when I press the Cancel
button with an empty form, I get a Please fill out this field.
error instead of returning to my home page (see views.py
for logic). So how can I get my app to ignore the DataRequired
validators when I press the Cancel
button?
forms.py
:
class ItemForm(FlaskForm):
id = StringField('id', validators=[DataRequired()]
name = StringField('Name', validators=[DataRequired()]
cancel = SubmitField('Cancel')
submit = SubmitField('Submit')
views.py
:
def add_item()
form = ItemForm()
if form.validate_on_submit():
if form.submit.data:
# Code to add item to db, removed for brevity.
elif form.cancel.data:
flash('Add operation cancelled')
return redirect(url_for('home.homepage'))
推荐答案
您的取消"按钮实际上不一定是提交"按钮.您可以简单地使用一个普通按钮将用户带回到首页(使用 href
或捕获 onclick
事件).
Your cancel button doesn't really need to be a submit button. You can simply have a normal button which takes the user back to the home page (using a href
or capturing the onclick
event).
如果您仍然希望 cancel
按钮成为WTForms字段,则一个选项是覆盖表单中的 validate
方法并删除 DataRequired
验证器上的 id
和 name
.以下内容未经测试,但可能会为您提供一个起点.
If you still want the cancel
button to be a WTForms field, one option would be to override the validate
method in the form and remove the DataRequired
validators on id
and name
. The below is untested but may give you a starting point to work from.
class ItemForm(FlaskForm):
id = StringField('id')
name = StringField('Name')
cancel = SubmitField('Cancel')
submit = SubmitField('Submit')
def validate(self):
rv = Form.validate(self)
if not rv:
return False
if self.cancel.data
return True
if self.id.data is None or self.name.data is None:
return False
return True
这篇关于如何忽略flask-wtf中的字段验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!