如何在表单的__init__函数中绑定字段 [英] How to bind a field in __init__ function of a form

查看:44
本文介绍了如何在表单的__init__函数中绑定字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Example_Form(Form):
    field_1 = TextAreaField()
    field_2 = TextAreaField()

    def __init__(self, type, **kwargs):
        super(Example_Form, self).__init__(**kwargs)

        if type == 'type_1':
           self.field_3 = TextAreaField()

在某些情况下,我需要将字段动态添加到表单中.添加到示例表单中的field_3原来是UnboundField.我试图将field_3绑定到__init__函数中的表单,但是它将不起作用.

In some scenarios I need to dynamically add fields into the form. The field_3 added to example form turns out to be a UnboundField. I tried to bind field_3 to form in __init__ function, but it won't work.

field_3 = TextAreaField()
field_3.bind(self, 'field_3')

如何将field_3绑定到示例表单?

How to bind field_3 to example form?

推荐答案

使用self.meta.bind_field创建绑定字段,并将其分配给实例和_fields字典.

Use self.meta.bind_field to create a bound field, and assign it to the instance and the _fields dict.

self.field_3 = self._fields['field_3'] = self.meta.bind_field(
    self, TextAreaField(),
    {'name': 'field_3', 'prefix': self._prefix}
)


在大多数情况下,在创建表单实例时使用子类并决定要使用哪个类是更清楚的事情.


In most cases, it's more clear to use a subclass and decide which class to use when creating the form instance.

class F1(Form):
    x = StringField()

class F2(F1):
    y = StringField()

form = F1() if type == 1 else F2()

如果需要提高动态性,可以将表单子类化并为其分配字段.与实例不同,直接将字段分配给类是有效的.

If you need to be more dynamic, you can subclass the form and assign fields to it. Assigning fields to classes works directly, unlike with instances.

class F3(F1):
    pass

if type == 3:
    F3.z = StringField()

form = F3()

您还可以定义所有字段,然后选择在验证表单之前删除一些字段.

You can also define all fields, then choose to delete some before validating the form.

class F(Form):
    x = StringField()
    y = StringField()

form = F()

if type == 1:
    del form.y

这篇关于如何在表单的__init__函数中绑定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆