Flask FieldForm RequiredIf逻辑

2024-10-01 05:06:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我似乎无法理解这一点。我需要一些帮助

我有这个forms.py,假设国家设置为:

class RequiredIfNot(DataRequired):
    """Validator which makes a field required if another field is set and has a truthy value.

    Sources:
        - http://wtforms.simplecodes.com/docs/1.0.1/validators.html
        - http://stackoverflow.com/questions/8463209/how-to-make-a-field-conditionally-optional-in-wtforms
        - https://gist.github.com/devxoul/7638142#file-wtf_required_if-py
    """
    field_flags = ('requiredif',)

    def __init__(self, message=None, *args, **kwargs):
        super(RequiredIfNot).__init__()
        self.message = message
        self.conditions = kwargs

    # field is requiring that name field in the form is data value in the form
    def __call__(self, form, field):

        for name, data in self.conditions.items():

            other_field = form[name]

            if other_field is None:
                raise Exception("No field named {} in form".format(name))

            if other_field.data != data and not field.data:
                DataRequired.__call__(self, form, field)

            Optional()(form, field)


class ItemsForm(FlaskForm):
    item_description = StringField(
        'Item description', [
            RequiredIfNot(country_code="DE", message='Item description is required')
        ]
    )

class MainForm(FlaskForm):
    country_code = SelectField(
        'Destination country', [
            validators.Required()
        ],
        choices=COUNTRIES,
        default = "DE"
    )

    number = StringField(
        'Invoice number', [
            RequiredIfNot(country_code="DE", message='Invoice number is required')
        ]
    )
    items = FieldList(
        FormField(ItemsForm),
        min_entries=1
    )

如何调整RequiredIf()函数,使其在MainForm()和ItemsForm()中的项中都能工作

ItemsForm表单抱怨它找不到country_code,这是有道理的,因为它是在另一个表单中

我希望我的问题是明确的,如果需要更多的信息让我知道


Tags: nameinselfformfieldmessagedataif