Flask WTForm:基于多个表单字段的自定义验证

问题描述 投票:0回答:1

我一直坚持为我的 Flask 表单创建验证器,我遵循了其他问题/链的说明,但没有一个起作用。

以下是我的表格:

class RegisterForm(FlaskForm):
    artist = BooleanField("Are you an artist?", default=False)
    organiser = BooleanField("Do you organise events?", default=False)
    dj = BooleanField("Are you a DJ?", default=False)

    proof_photo = FileField(label="Upload proof photo (artists and/ or organisers, only)", description="Please upload a photo proof", validators=[FileAllowed(['jpg', 'png'], 'JPG or PNG only, please.'))
    proof = StringField("Evidence of being artist/ organiser", description="URL to your videos")
    submit = SubmitField("Sign me up!")

我想做的是,如果以下三个中的任何一个:艺术家、组织者dj被勾选为True,那么字段proof_photoproof将成为必填字段。

我在下面尝试过,但不幸的是它不起作用,我不确定我做错了什么。

def authorisation_check(self):
    if not super(RegisterForm, self).validate():
        return False
    if (self.artist.data == True or self.organiser.data == True or self.dj.data == True) and  not (self.proof_photo.data and self.proof.data):
        msg = 'Please submit your proof'
        self.proof_photo.errors.append(msg)
        self.proof.errors.append(msg)
        return False
    return True

如果有人可以帮助我解决这个问题,我将不胜感激:) 谢谢

python flask flask-wtforms
1个回答
0
投票

在下面的示例中,我编写了两个接受依赖字段名称的自定义验证器。根据指定字段中的输入,执行验证并在必要时抛出错误。

from flask import (
    Flask, 
    render_template
)
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed, FileRequired
from wtforms import BooleanField, StringField, SubmitField
from wtforms.validators import DataRequired

app = Flask(__name__)
app.secret_key = 'your secret here'

class DependentFileRequired(FileRequired):
    def __init__(self, fieldnames, message=None):
        super().__init__(message)
        self.fieldnames = fieldnames
        self.field_flags = {}

    def __call__(self, form, field):
        if any(form[name].data and \
            (not isinstance(form[name].data, str) or form[name].data.strip()) \
            for name in self.fieldnames
        ):
            super().__call__(form, field)

class DependentDataRequired(DataRequired):
    def __init__(self, fieldnames, message=None):
        super().__init__(message)
        self.fieldnames = fieldnames
        self.field_flags = {}

    def __call__(self, form, field):
        if any(form[name].data and \
            (not isinstance(form[name].data, str) or form[name].data.strip()) \
            for name in self.fieldnames
        ):
            super().__call__(form, field)

class RegisterForm(FlaskForm):
    artist = BooleanField("Are you an artist?", default=False)
    organiser = BooleanField("Do you organise events?", default=False)
    dj = BooleanField("Are you a DJ?", default=False)

    proof_photo = FileField(
        label="Upload proof photo (artists and/ or organisers, only)", 
        description="Please upload a photo proof", 
        validators=[
            DependentFileRequired(fieldnames=['artist', 'organiser', 'dj']), 
            FileAllowed(['jpg', 'png'], 'JPG or PNG only, please.')
    ])
    proof = StringField(
        "Evidence of being artist/ organiser", #
        description="URL to your videos", 
        validators=[
            DependentDataRequired(fieldnames=['artist', 'organiser', 'dj'])
        ]
    )
    submit = SubmitField("Sign me up!")


@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        print(form.data)
    return render_template('register.html', **locals())
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Register</title>
</head>
<body>
    <form method="post">
        {{ form.hidden_tag() }}
        <div>
            {{ form.artist.label() }}
            {{ form.artist() }}
        </div>
        <div>
            {{ form.organiser.label() }}
            {{ form.organiser() }}
        </div>
        <div>
            {{ form.dj.label() }}
            {{ form.dj() }}
        </div>
        <div>
            {{ form.proof_photo.label() }}
            {{ form.proof_photo() }}
            {% if form.proof_photo.errors -%}
            <ul>
                {% for err in form.proof_photo.errors -%}
                <li>{{ err }}</li>
                {% endfor -%}
            </ul>
            {% endif -%}
        </div>
        <div>
            {{ form.proof.label() }}
            {{ form.proof() }}
            {% if form.proof.errors -%}
            <ul>
                {% for err in form.proof.errors -%}
                <li>{{ err }}</li>
                {% endfor -%}
            </ul>
            {% endif -%}
        </div>
        {{ form.submit() }}
    </form>
</body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.