可变长度元素的动态形式:wtforms

blu*_*ank 5 python forms wtforms

我正在使用 wtforms,我需要创建一个可以根据数据库中的信息生成表单定义的东西;动态表单创建。我逐渐意识到需要做什么,而我才刚刚开始。我可以创建表单并将它们与 wtforms/flask 一起使用,但是根据数据定义表单(从表单到表单略有不同)目前超出了我目前的技能水平。

有没有人做过这个并提供一些意见?有点模糊的问题,还没有实际的代码。我还没有找到任何例子,但也不是不可能做到。

mass of variable data to be used in a form --> wtforms ---> form on webpage
Run Code Online (Sandbox Code Playgroud)

编辑:

因此,“例如”我们可以使用调查。一个调查由几个 SQLAlcehmy 模型组成。调查是具有任意数量关联问题模型的模型(问题属于调查,例如多项选择问题,它变得复杂)。为了简化,让我们使用简单的 json/dict 伪代码:

{survey:"Number One",
    questions:{
        question:{type:truefalse, field:"Is this true or false"},
        question:{type:truefalse, field:"Is this true or false"},
        question:{type:text, field:"Place your X here"}
     } 
 }

{survey:"Number Two",
    questions:{
        question:{type:text, field:"Answer the question"},
        question:{type:truefalse, field:"Is this true or false"},
        question:{type:text, field:"Place your email address here"}
     } 
 }
Run Code Online (Sandbox Code Playgroud)

想象一下,而不是这个,数百个不同长度的 5+ 字段类型。如何使用 WTForms 为此管理表单,或者我什至需要使用 wtforms?我可以根据需要定义静态表单,但不能动态定义。

顺便说一句,我在 rails 中使用 simpleform 做了类似的事情,但是当我在 Python atm 中工作时(在不同的事情上,我以调查事物为例,但问题/字段/答案事物抽象了一个我需要的许多类型的输入)。

所以是的,我可能需要建造某种工厂,这样做需要我一些时间,例如:

http://wtforms.simplecodes.com/docs/1.0.2/specific_problems.html

https://groups.google.com/forum/?fromgroups=#!topic/wtforms/cJl3aqzZieA

Sea*_*ira 4

只需在运行时将适当的字段添加到基本表单即可。以下是您可以如何执行此操作的草图(尽管非常简化):

class BaseSurveyForm(Form):
    # define your base fields here


def show_survey(survey_id):
    survey_information = get_survey_info(survey_id)

    class SurveyInstance(BaseSurveyForm):
        pass

    for question in survey_information:
        field = generate_field_for_question(question)
        setattr(SurveyInstanceForm, question.backend_name, field)

    form = SurveyInstanceForm(request.form)

    # Do whatever you need to with form here


def generate_field_for_question(question):
    if question.type == "truefalse":
        return BooleanField(question.text)
    elif question.type == "date":
        return DateField(question.text)
    else:
        return TextField(question.text)
Run Code Online (Sandbox Code Playgroud)