WTForm 使表单字段不可编辑

时间:2021-07-05 13:05:18

标签: flask flask-wtforms

所以我有一个 WTForm,我需要条件 required 属性并使用这个 SO answer

class RequiredIf(Required):
    # a validator which makes a field required if
    # another field is set and has a truthy value

    def __init__(self, other_field_name, *args, **kwargs):
        self.other_field_name = other_field_name
        super(RequiredIf, self).__init__(*args, **kwargs)

    def __call__(self, form, field):
        other_field = form._fields.get(self.other_field_name)
        if other_field is None:
            raise Exception('no field named "%s" in form' % self.other_field_name)
        if bool(other_field.data):
            super(RequiredIf, self).__call__(form, field)

问题是,另一个字段不是表单字段,而是来自我正在填充的 obj (form = DemandeForm(obj=demande)) 的属性。

据我所知,无法访问不是 obj 属性的 Form 属性。 这是正确的吗?

所以我确实将条目添加为 Field

    TelephoneProfessionnel_EstObligatoire = BooleanField()
    TelephoneProfessionnel_ClePays = SelectWithOptionsField(
        'Code Tél Professionnel',
        [RequiredIf('TelephoneProfessionnel_EstObligatoire')],
        choices=tel_prefix_choices()
    )

但此 TelephoneProfessionnel_EstObligatoire 字段不得在任何情况下由表单编辑。

因此,我需要确保它不能被编辑。

我尝试创建自定义 ReadOnlyField,但没有成功:

from wtforms import BooleanField

class ReadonlyField(BooleanField):
    def process_formdata(self, value):
        print('Do nothing with')
        print(value)
        print(self.data)

没有成功:(

谁能帮我解决这个问题?要么将该值存储在 Form 中的某处,要么创建一个始终等于 Field 值的安全只读 obj

谢谢

0 个答案:

没有答案
相关问题