[英]How can I create repetitive form elements in a DRY way with Flask-WTForms?
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. 我有一个WTForms表单,我希望用户能够上传最多10张图像,并提供图像标题和字幕。 Currently I declare all 10 sets of fields, but this seems redundant.
目前,我声明了所有10组字段,但这似乎是多余的。 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...
You can get what you're looking for by combining FormField
with FieldList
: 您可以通过将
FormField
与FieldList
结合使用来获得FieldList
:
class ImageForm(Form):
image = FileField('Upload')
caption = StringField('Caption')
credit = StringField('Credit')
class MyForm(Form):
images = FieldList(FormField(ImageForm), min_entries=10)
You can then access the individual ImageForm
instances either through my_form_instance.images.entries
or by iterating over my_form_instance.images
: 然后,您可以通过
my_form_instance.images.entries
或通过对my_form_instance.images
进行迭代来访问各个ImageForm
实例:
for image in my_form_instance.images:
print(image.data['caption'], image.data['credit'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.