Dynamic forms from variable length elements: wtforms

我的未来我决定 提交于 2019-12-03 17:28:43

Simply add the appropriate fields to the base form at run time. Here's a sketch of how you might do it (albeit much simplified):

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)
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)

I use the extended class BaseForm for all my forms and have a convenient append_field function on class.

Returns the class with the field appended, since instances (of Form fields) can't append fields.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!