Disabled field is considered for validation in WTForms and Flask

后端 未结 4 880
别跟我提以往
别跟我提以往 2021-02-01 08:38

I have some fields in page disabled as for example:(using jinja2 templating system)



{{ form.na
4条回答
  •  名媛妹妹
    2021-02-01 09:16

    I defined my own validator for this problem:

    from wtforms.validators import Optional
    
    class OptionalIfDisabled(Optional):
    
        def __call__(self, form, field):
            if field.render_kw is not None and field.render_kw.get('disabled', False):
                field.flags.disabled = True
                super(OptionalIfDisabled, self).__call__(form, field)
    

    And then I defined a new base for my forms:

    from wtforms.form import Form
    
    class BaseForm(Form):
    
        def populate_obj(self, obj):
            for name, field in self._fields.items():
                if not field.flags.disabled:
                    field.populate_obj(obj, name)
    

    Now every form can extend the BaseForm and disable fields like this:

    from wtforms.fields import StringField, SubmitField
    
    class TeamForm(BaseForm):
        team = StringField(label='Team Name', 
                           validators=[OptionalIfDisabled(), InputRequired()]
        submit = SubmitField(label='Submit')
    
        def __init__(self, *args, **kwargs):
            super(TeamForm, self).__init__(*args, **kwargs)
            # disable the fields if you want to
            if some_condition:
                self.team.render_kw = {'disabled': True}
    

    After validation of the TeamForm, you can use populate_obj to copy the enabled form data in any object. It will ignore the disabled fields.

提交回复
热议问题