1 回答

TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超8個(gè)贊
我似乎已經(jīng)通過這個(gè)問題獲得了我想要的結(jié)果。我原來的問題的一部分實(shí)際上與我沒有在我的問題中發(fā)布的視圖中的一些代碼有關(guān)。
在 上,我將(突出顯示的選項(xiàng))if form.validate_on_submit():中的標(biāo)簽附加到我的. 在帖子已經(jīng)附加標(biāo)簽的情況下,這意味著取消選擇字段中的默認(rèn)值確實(shí)會(huì)根據(jù)需要清空,但無論如何仍然有原始數(shù)據(jù),因此沒有變化。form.tags.datapost.tagsform.tags.datapost.tags
這是通過以下方式解決的:
# empty tags list then add highlighted choices
post.tags = []
for id in form.tags.data:
t = Tag.query.filter_by(id=id).first()
post.tags.append(t)
我還更改了填充表單的代碼,使其更簡單。我錯(cuò)了需要使用defaultover data(坦率地說,我不明白兩者之間的區(qū)別):
# populate form, blank for new post
form = EditorForm(obj=post)
# populate tags field
form.tags.choices = [(tag.id, tag.tag) for tag in Tag.query.order_by('tag')]
# populate defaults only on GET otherwise user choice overidden
if request.method == 'GET':
# declare default (highlighted) tags list
form.tags.data = []
# if post has tags, highlight them
if post.tags:
for tag in post.tags:
form.tags.data.append(tag.id)
添加回答
舉報(bào)