首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FileField字段的填充

FileField字段的填充
EN

Stack Overflow用户
提问于 2021-09-24 09:47:02
回答 1查看 444关注 0票数 2

我有一个使用WTF的表格-在水瓶上的表格,例如:

代码语言:javascript
复制
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 )打开表单页面,则将存储的信息预先填充表单,如:

代码语言:javascript
复制
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。

代码语言:javascript
复制
print(type(file))
print(file)
print(type(ImageForm.image))
print(ImageForm.image)

给予:

代码语言:javascript
复制
<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字段方面有经验?你能帮我吗?

非常感谢!

EN

回答 1

Stack Overflow用户

发布于 2022-11-24 00:42:34

我知道现在很晚了,但我写这个答案是因为我被困在了同一个问题上。出于安全考虑,浏览器不接受预先填充的FileField。您需要用html显示图像,并保留用于更新图像的FileField。要知道FileField是否包含新的文件存储,可以检查其类型。如果是字符串,则不会插入新文件:

代码语言:javascript
复制
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.

我希望这是明确的,并将帮助某人。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69312929

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档