内置相互关联的数据字段验证烧瓶WTF

时间:2019-02-15 12:02:31

标签: python flask flask-wtforms

我有一个预订表格类,定义为

class Booking(FlaskForm):
    room_type= HiddenField()
    check_in=DateField("Arrival Date",  [validators.Required("Select Arrival Date")], format='%Y-%m-%d')
    check_out=DateField("Departure Date",  [validators.Required("Select Departure Date")], format='%Y-%m-%d')
    adults = TextField("Adults",[validators.Required("No of Adults travelling are Mandatory!")])
    children = TextField("Children")
    name_booking = TextField("Name",[validators.Required("First Name is Mandatory!")])
    email_booking = EmailField("email ",[validators.Required("email is Mandatory!")])
    submit = SubmitField("Send")

我想建立一种逻辑,使签到始终少于签出。我尝试过

def chkdate(form, field):
    if field.data > check_in.data:
        raise ValidationError('Check Out cannot be before Check In')

class Booking(FlaskForm):
    room_type= HiddenField()
    check_in=DateField("Arrival Date",  [validators.Required("Select Arrival Date")], format='%Y-%m-%d')
    check_out=DateField("Departure Date",  [validators.Required("Select Departure Date"), chkdate()], format='%Y-%m-%d')
    adults = TextField("Adults",[validators.Required("No of Adults travelling are Mandatory!")])

基于WTF Docs

1 个答案:

答案 0 :(得分:0)

首先,方法名称必须采用validate_checkdate的形式,其次,它必须是Booking类的方法,而不是单独的函数。

因此更新代码如下所示

class Booking(FlaskForm):
    room_type= HiddenField()
    check_in=DateField("Arrival Date",  [validators.Required("Select Arrival Date")], format='%Y-%m-%d')
    check_out=DateField("Departure Date",  [validators.Required("Select Departure Date"), chkdate()], format='%Y-%m-%d')
    adults = TextField("Adults",[validators.Required("No of Adults travelling are Mandatory!")])

    def validate_chkdate(form, field):
        if field.data > check_in.data:
            raise ValidationError('Check Out cannot be before Check In')