在 Colander 和 Deform 中强制创建映射模式序列

Impreratively creating sequence of mapping schemas in Colander and Deform

我正在构建一个页面,用户可以在该页面上对 Colander 和 Deform 中的任意数量的产品发表评论。我已经掌握了所有必需的元素,但在连接点方面仍然存在一些问题。具体来说,我如何命令式地(动态地)创建一个包含 N 个表单项的序列,然后为它们绑定数据?

这是我到目前为止的尝试:

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

好的 - 明白了。最里面的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()