我有一个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...
答案 0 :(得分:3)
您可以将FormField
与FieldList
合并来获取您正在寻找的内容:
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'])