如何使用Flask-WTForms以干燥的方式创建重复的表单元素?

时间:2016-06-14 01:35:30

标签: python flask wtforms flask-wtforms

我有一个WTForms表单,我希望用户能够上传最多10张图片,还可以提供图片标题和图片。目前我宣布所有10组字段,但这似乎是多余的。有没有办法用动态名称创建表单字段,所以我可以在循环中创建它们?

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...

1 个答案:

答案 0 :(得分:3)

您可以将FormFieldFieldList合并来获取您正在寻找的内容:

class ImageForm(Form):
    image = FileField('Upload')
    caption = StringField('Caption')
    credit = StringField('Credit')

class MyForm(Form):
    images = FieldList(FormField(ImageForm), min_entries=10)

然后,您可以通过ImageForm或迭代my_form_instance.images.entries来访问各个my_form_instance.images个实例:

for image in my_form_instance.images:
    print(image.data['caption'], image.data['credit'])