简体   繁体   中英

Flask form.populate_obj() keep null values

I have an edit function where I edit certain data. The form (I use flask_wtf) is the same, so I can use:

form.populate_obj(build)

Now I see all old values and can edit them, but some fields do not have a value. These fields are null in the DB. Often I dont need to edit them so I simply ignore them.

And here is the problem, if I submit the edit form all values which should remain null become an empty string ""

Here is a precise example:

Thats an entry where I want only to edit date_added . I ignore bandits and additional_info . 在此处输入图片说明

After submit I expect that bandits and additional_info still are null , but they change:

在此处输入图片说明

Of course I could rewrite the whole code and use the same logic where I add these values to the DB, but I feel like there should be a better solution.

Could you add filters to your form fields:

filters = [lambda x: x or None]

For example like this:

birthtown = StringField("Birthtown", filters = [lambda x: x or None])

This will either use whatever you write in the field or None. At least you will get rid of the empty strings. Or is this too much rewriting to be acceptable?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM