我有一个使用WTF的表格-在水瓶上的表格,例如:
class ImageForm(FlaskForm):
"""Form used for image uploading"""
image = FileField(
validators=[
FileRequired(),
FileAllowed(["png", "jpg", "jpeg"], "This file is not a valid image !",),
],
render_kw={"class": "form-control-file border"},
)
patient_ID = StringField(
"patient_ID",
validators=[DataRequired()],
render_kw={"placeholder": "Patient ID", "class": "form-control"},
)
submit = SubmitField("Upload", render_kw={"class": "btn btn-primary mb-2"})填好后效果很好。不过,我希望人们以后能够修改这些信息。因此,我要做的是,如果使用GET args (如id=1 )打开表单页面,则将存储的信息预先填充表单,如:
if request.args:
image_request = Image.query.get(request.args.get("id"))
# Check that image exists in DB and prepare the FileStoage object.
if image_request is not None:
file = None
with open(image_request.image_path, "rb") as fp:
file = FileStorage(fp)
form = ImageForm(
image=file,
patient_ID=image_request.patient_id)它适用于patient_ID,它是正确填充的。然而,“图像”字段停留在UnboundFile。
print(type(file))
print(file)
print(type(ImageForm.image))
print(ImageForm.image)给予:
<class 'werkzeug.datastructures.FileStorage'>
<FileStorage: '/home/xxx/xxx/data/hkjhk/hkjhk_dog.jpg' (None)>
<class 'wtforms.fields.core.UnboundField'>
<UnboundField(FileField, (), {'validators': [<flask_wtf.file.FileRequired object at 0x7f170969fb20>, <flask_wtf.file.FileAllowed object at 0x7f170969ffd0>], 'render_kw': {'class': 'form-control-file border'}})>有没有人在如何预填FileStorage字段方面有经验?你能帮我吗?
非常感谢!
发布于 2022-11-24 00:42:34
我知道现在很晚了,但我写这个答案是因为我被困在了同一个问题上。出于安全考虑,浏览器不接受预先填充的FileField。您需要用html显示图像,并保留用于更新图像的FileField。要知道FileField是否包含新的文件存储,可以检查其类型。如果是字符串,则不会插入新文件:
if imageForm.image.data and not sinstance(form.imageFile.data, str):
# here you have a new image file
else:
# here the FileField contains a string or is empty meaning that the
# user has no intention of changing or adding a file.我希望这是明确的,并将帮助某人。
https://stackoverflow.com/questions/69312929
复制相似问题