我可以在__init__ wtforms中添加字段吗?

时间:2016-02-14 03:28:08

标签: python wtforms flask-wtforms

由于某种原因,我需要在__init__()内声明一个字段,这样我就可以制作任意类型的FormField

form.py

为例
class PurchaseForm(Form):
    item_class = ItemForm
    transaction_items = FieldList(FormField(item_class),
                                  label='items',
                                  min_entries=1)

    def __init__(self, item_class, *args, **kwargs):
       super().__init__(*args, **kwargs)
       self.item_class = item_class
       self.transaction_items = FieldList(FormField(self.item_class),
                                           label='items',
                                           min_entries=1)

如果我这样做,transaction_items字段不会被__init__()替换,我可以做一些事情来覆盖它吗?或针对此特定实例执行setattr之类的操作?

编辑:这是我指定构造函数的方法

import form

@app.route('/add/purchase-transaction', methods=['GET', 'POST'])
def add_purchase_transaction():
    form = forms.PurchaseForm(form.ItemForm)

    if form.validate_on_submit():
        # do something

    return render_template('add-purchase-transaction.html', form=form)

所以我的目标是制作一个PurchaseForm,其中FieldList包含ItemForm表单类,将来我可以将ItemForm交换到不同的类,例如到PurchaseItemForm

1 个答案:

答案 0 :(得分:5)

首先,我认为您的super().__init__(*args, **kwargs)无效,应该是super(PurchaseForm, self).__init__(*args, **kwargs) - 我们能够像这样运行您的代码吗?

另外,你怎么能说它不起作用 - 从这段代码中查看一个创建的表单 - 它看起来没问题:

class ItemForm(Form):
    openid = StringField('openid', validators=[])
    remember_me = BooleanField('remember_me', default=False)

class PurchaseForm(Form):
    item_class = ItemForm
    transaction_items = None

    def __init__(self, item_class, *args, **kwargs):
        super(PurchaseForm, self).__init__(*args, **kwargs)
        self.item_class = item_class
        self.transaction_items = FieldList(FormField(self.item_class),
                                           label='items',
                                           min_entries=1)