如何使用Flask-WTForms以DRY方式创建重复的表单元素? [英] How can I create repetitive form elements in a DRY way with Flask-WTForms?
问题描述
我有一个WTForms表单,我希望用户能够上传最多10张图像,并提供图像标题和字幕.目前,我声明了所有10组字段,但这似乎是多余的.有没有一种方法可以使用动态名称创建表单字段,所以我可以循环创建它们?
I have a WTForms form where I want the user to be able to upload up to 10 images, and also give the images captions and credits. Currently I declare all 10 sets of fields, but this seems redundant. Is there a way to create form fields with dynamic names, so I could create them in a loop?
class MyForm(Form):
image1 = FileField('Upload')
image1_caption = StringField('Caption')
image1_credit = StringField('Credit')
image2 = FileField('Upload')
image2_caption = StringField('Caption')
image2_credit = StringField('Credit')
# ...through 10 images...
推荐答案
通过结合 FieldList
:
You can get what you're looking for by combining FormField
with FieldList
:
class ImageForm(Form):
image = FileField('Upload')
caption = StringField('Caption')
credit = StringField('Credit')
class MyForm(Form):
images = FieldList(FormField(ImageForm), min_entries=10)
然后您可以通过my_form_instance.images.entries
或遍历my_form_instance.images
来访问各个ImageForm
实例:
You can then access the individual ImageForm
instances either through my_form_instance.images.entries
or by iterating over my_form_instance.images
:
for image in my_form_instance.images:
print(image.data['caption'], image.data['credit'])
这篇关于如何使用Flask-WTForms以DRY方式创建重复的表单元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!