2015-05-17 54 views
1

我正在構建一個頁面,用戶可以在Colander和Deform中爲任意數量的產品留下評論。我掌握了所有必需的元素,但我仍然存在一些連接點的問題。具體而言,我如何可以(動態地)創建一系列N個表單項,然後爲它們綁定數據?在Colander和Deform中創建映射模式序列

這是我這麼遠的嘗試:

reviews =[ 
     { 
      "product": "Shampoo", 
      "comment": "" 
      "rating": 3, 
     }, 

     { 
      "product": "Soap", 
      "comment": "", 
      "rating:" 3, 
     }, 
    ] 

rating = colander.Schema() 
rating.add(colander.SchemaNode(colander.Int(), name="rating", missing=colander.null, validator=colander.Range(1, 5))) 
rating.add(colander.SchemaNode(colander.String(), name="comment", validator=colander.Length(max=4096), missing="")) 
ratings = colander.SequenceSchema(name="ratings", default=reviews, children=[rating]) 

# schema.add(colander.SchemaNode(colander.Sequence(), rating, name="ratings", default=reviews)) 
schema = CSRFSchema() 
schema.add(ratings) 

form = deform.Form(schema) 
if request.method == "POST": 
    controls = request.POST.items() 

    try: 
     captured = form.validate(controls) 
    except deform.ValidationFailure as e: 
     return {'form': e.render()} 
else: 
    rendered_form = form.render() 

return locals() 

但是這會導致錯誤:

ValueError: Prototype for <deform.field.Field object at 4576735072 (schemanode 'ratings')> has no name 
+0

請修正代碼突出顯示 –

回答

0

確定 - 它了。最內層的SchemaNode()必須命名。必須使用colander.SchemaNode(colander.Sequence())來映射出項目的順序。

reviews =[ 
     { 
      "product": "Shampoo", 
      "comment": "", 
      "rating": 3, 
     }, 

     { 
      "product": "Soap", 
      "comment": "", 
      "rating": 3, 
     }, 
    ] 

rating = colander.Schema(name="single_rating") 
rating.add(colander.SchemaNode(colander.Int(), name="rating", missing=colander.null, validator=colander.Range(1, 5))) 
rating.add(colander.SchemaNode(colander.String(), name="comment", validator=colander.Length(max=4096), missing="")) 
ratings = colander.SchemaNode(colander.Sequence(), rating, name="ratings", default=reviews) 

# schema.add(colander.SchemaNode(colander.Sequence(), rating, name="ratings", default=reviews)) 
schema = CSRFSchema() 
schema.add(ratings) 

form = deform.Form(schema) 
if request.method == "POST": 
    controls = request.POST.items() 

    try: 
     captured = form.validate(controls) 
    except deform.ValidationFailure as e: 
     return {'form': e.render()} 
else: 
    rendered_form = form.render() 

return locals()