for some reason I need to declare a field inside the __init__()
so I can make arbitrary type of FormField
.
Take for example in 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)
If I do it like that, the transaction_items
field is not replaced by the __init__()
, can I do something to override it? or do something like setattr
for this specific instance?
Edit: Here is how I specify the constructor
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)
So my goal is to make a PurchaseForm
which has a FieldList
containing ItemForm
form class, and in the future I can swap ItemForm
to different class, for example to PurchaseItemForm
WTForms is a Python library that provides flexible web form rendering. You can use it to render text fields, text areas, password fields, radio buttons, and others. WTForms also provides powerful data validation using different validators, which validate that the data the user submits meets certain criteria you define.
StringField (default field arguments)[source] This field is the base for most of the more complicated fields, and represents an <input type="text"> .
From version 0.9. 0, Flask-WTF will not import anything from wtforms, you need to import fields from wtforms. If your form has multiple hidden fields, you can render them in one block using hidden_tag() .
To start with, I think your super().__init__(*args, **kwargs)
is not valid and should be super(PurchaseForm, self).__init__(*args, **kwargs)
- we're you able to run your code like that?
Also, how can you tell it's not working - looking into a created form from this code - it looks ok:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With