1
我在使用瓶WTF這個命名約定形式幾個要素...如何使用字符串從窗體訪問嵌套屬性?
# req_app_qty
# req_app_note
# req_main_qty
# req_main_note
# req_side_qty
# req_side_note
# req_bread_qty
# req_bread_note
# continued...
我可以手動訪問表單數據是這樣的...
print "Manually (qty): " , form.req_app_qty.data # works fine
print "Manually (note): " , form.req_app_note.data # works fine
但我想訪問此表單數據,更自動化的方式...
categories = [ "app", "main", "side", "bread", "dessert", "bev", "uten", "cups", "misc"]
for x in categories:
field1 = "req_%s_qty.data" % x # create a string to represent the attributes
field2 = "req_%s_note.data" % x # create a string to represent the attributes
qty_rqst = form.field1.data # fails
rqst_note = form.field2.data # fails
# also tried
print "QTY=", getattr(form, field1) # fails
print "Note:", getattr(form, field2) # fails
我嘗試了上述這些方法,他們都失敗了......
第一種方法行失敗,出現錯誤,指出表單沒有屬性'field1'或'field2'。
至於訪問表單數據的第二個方法,下面幾行失敗,一個錯誤,指出沒有屬性「req_app_qty.data」
print "QTY=", getattr(form, field1) # fails
如何創建一個字符串訪問這些表單屬性?
根據您的回答,我的類別做了以下修改來解決問題.. 對於x req_%s_note「%x#創建一個字符串來表示屬性 qty_rqst = getattr(form,field1).data#now works rqst_note = getattr(form,field2).data#now works now – marvcode