如何使用字符串从表单中访问嵌套属性?

时间:2016-04-02 23:26:13

标签: python-2.7 flask-wtforms getattr

我使用带有此命名约定的Flask 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  

如何创建字符串以访问这些表单属性?

1 个答案:

答案 0 :(得分:0)

qty_rqst = form.field1.data           # fails

这不起作用,因为您尝试访问不存在的字段field1

print "QTY=", getattr(form, field1)   # fails

这不起作用,因为您尝试访问不存在的字段req_X_qty.data

您需要访问存在的字段,例如

print 'QTY=', getattr(form, 'req_app_qty').data