从可变长度元件的动态形式:wtforms(Dynamic forms from variable l

2019-07-31 11:48发布

我使用wtforms,我需要创建一个东西,将基于关闭数据库中的信息的表单定义; 动态表单创建。 我得到的,需要做的事情的感觉,我才刚刚开始。 我可以创建形式和wtforms /瓶,但是从定义数据表将从形式略有不同,形成目前超出了我目前的技术水平中使用它们。

有没有人这样做,有一定的输入提供的? 有点模糊的问题,没有实际的代码呢。 我还没有发现任何的例子,但它也不是不可能的事情。

mass of variable data to be used in a form --> wtforms ---> form on webpage

编辑:

所以,一个“例如”我们可以使用调查。 调查由几个SQLAlcehmy模型。 调查是与任意数量的相关问题车型的模型(问题属于调查和情况就变得复杂了说,多项选择题)。 为了简化,让我们用简单的JSON /字典的伪码:

{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"}
     } 
 }

想象一下,而不是这个,有5+字段类型不同长度的数百个。 如何使用WTForms来管理这个形式,或者我甚至需要使用wtforms? 我可以定义静态的形式,我需要他们,而不是动态的,但。

顺便说一句我已经做了在轨像这样与simpleform但正如我在Python ATM(我工作在不同的东西,我使用的调查事,作为一个例子,但跨越的问题/场/答案的事情摘要我需要多种类型的输入)。

所以,是有可能,我会需要建立一些工厂,这样做会带我一段时间,例如:

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

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

Answer 1:

只需添加相应的字段在运行时的基本形式。 这里有一个如何做到这一点(虽然大大简化) 草图

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)


Answer 2:

class BaseForm(Form):
    @classmethod
    def append_field(cls, name, field):
        setattr(cls, name, field)
        return cls

from forms import TestForm
form = TestForm.append_field("do_you_want_fries_with_that",BooleanField('fries'))(obj=db_populate_object)

我用我的所有形式的扩展类基本形式 ,并有一流的便捷append_field功能。

返回与所附领域的类中,由于(的表单字段)实例不能追加字段。



文章来源: Dynamic forms from variable length elements: wtforms