WTForms创建可变数量的字段

时间:2012-07-24 00:41:50

标签: python wtforms

如何使用不同的问题动态创建一些表单字段,但答案相同?

from wtforms import Form, RadioField
from wtforms.validators import Required

class VariableForm(Form):

    def __init__(formdata=None, obj=None, prefix='', **kwargs):
        super(VariableForm, self).__init__(formdata, obj, prefix, **kwargs)
        questions = kwargs['questions']
        // How to to dynamically create three questions formatted as below?

    question = RadioField(
            # question ?,
            [Required()],
            choices = [('yes', 'Yes'), ('no', 'No')],
            )

questions = ("Do you like peas?", "Do you like tea?", "Are you nice?")  
form = VariableForm(questions = questions)

3 个答案:

答案 0 :(得分:12)

一直是in the docs

def my_view():
    class F(MyBaseForm):
        pass

    F.username = TextField('username')
    for name in iterate_some_model_dynamically():
        setattr(F, name, TextField(name.title()))

    form = F(request.POST, ...)
    # do view stuff

我没有意识到,在任何实例化发生之前,必须在中设置类属性。清晰度来自bitbucket comment

  

这不是一个错误,它是设计的。有很多问题   将字段添加到实例化表单 - 例如,数据进入   通过Form构造函数。

     

如果重新读取链接的线程,您会注意到需要派生类,向其中添加字段,然后实例化新类。通常,您将在视图处理程序中执行此操作。

答案 1 :(得分:1)

你快到了:

CHOICES = [('yes', 'Yes'), ('no', 'No')]

class VariableForm(Form):

    def __new__(cls, questions, **kwargs):
        for index, question in enumerate(questions):
            field_name = "question_{}".format(index)
            field = RadioField(question,
                                  validators=[Required()],
                                  choices=CHOICES)
            setattr(cls, field_name, field)
        return super(VariableForm, cls).__new__(cls, **kwargs)

答案 2 :(得分:0)

就我而言, 我使用了csv并使用pandas导入了它。

因此,该解决方案甚至可以根据需要使用不同的答案。

data=pd.read_csv("./temp.csv")
class UserForm(Form):
    for i in data:
        if data[i][0] == 'textbox':
            formElement='TextField("%s",validators=[validators.required()], default="please add content")' %(i)

        elif data[i][0] == 'radio':
            choice = list(data[i][1:].dropna().unique().tolist())
            choiceStr=''
            for k in choice:
               choiceStr +="('"+k+"','"+k+"'),"
            
            formElement = 'RadioField("%s",validators=[validators.required()],choices=[%s], default="%s")' %(i,choiceStr, choice[0])

        elif data[i][0] == 'dropdown':
            choice = list(data[i][1:].dropna().unique().tolist())
            # choice.remove('X')
            choiceStr=''
            for k in choice:
               choiceStr +="('"+k+"','"+k+"'),"
            
            formElement = 'SelectField("%s",validators=[validators.required()],choices=[%s])' %(i,choiceStr)


        exec("%s=%s" % (i,formElement))