flask 带下拉列表框的表单(flask 58)

2019-08-14 16:36:10 浏览数 (1)

带下拉列表框的表单,自定义错误验证validate_name(self,field)

class PostForm(FlaskForm): title=StringField('Title',validators=[DataRequired(),Length(1,60)]) category=SelectField('Category',coerce=int,default=1) body=CKEditorField('Body',validators=[DataRequired()]) submit=SubmitField()

代码语言:javascript复制
def __init__(self,*args,**kwargs):
    super(PostForm,self).__init__(*args,**kwargs)
    self.category.choices=[(category.id,category.name)
                           for category in Category.query.order_by(Category.name).all()]

class CategoryForm(FlaskForm): name=StringField('Name',validators=[DataRequired(),Length(1,30)]) submit=SubmitField()

代码语言:javascript复制
def validate_name(self,field):
    if Category.query.filter_by(name=field.data).first():
        raise ValidationError('Name already in use')

可以为空,或者必须为某种格式的验证

site = StringField('Site', validators=[Optional(), URL(), Length(0, 255)])

0 人点赞