【问题标题】:WTForms create variable number of fieldsWTForms 创建可变数量的字段
【发布时间】:2012-07-22 06:47:07
【问题描述】:

我如何动态创建一些具有不同问题但答案相同的表单域?

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)

【问题讨论】:

    标签: python wtforms


    【解决方案1】:

    一直是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 构造函数。

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

    【讨论】:

    • 我不清楚这个解决方案是否与我的问题有关。我的 Post 模型中有称为标签的关系...当我调用 PostForm 生成标签时,查询显示而不是查询结果。如何运行查询并将结果作为逗号分隔的字符串发送到 Post tags 字段?这是我的posted question。
    • 通过这种方式,它并不能明确解决问题,你不能像form.py然后a = Form(params)那样分离表单文件,在方法中定义类不被认为是好的做法? stackoverflow.com/questions/2583620/…
    【解决方案2】:

    你快到了:

    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)
    

    【讨论】:

    • 感谢您的回复。如果我这样做,所有字段都会显示为 UnboundFields 并且不会与表单一起呈现。
    • @ash - 抱歉 - 我认为应该是 __new__ 而不是 __init__。我已经用新的(仍然未经测试的)代码更新了我的答案。如果它不适合你,请告诉我。
    • 再次感谢您的回复,不幸的是这不起作用(我不得不做return super(VariableForm, cls).__new__(cls, **kwargs)。我一直在看bitbucket.org/simplecodes/wtforms/src/a5f9e30260cc/wtforms/…,但我不知道发生了什么。我会必须继续尝试其他事情。
    • 我正在尝试相同的方法,似乎更好的是我将我的逻辑留在 forms.py 中而不是在视图中,你能在最后用 new 创建它吗?我遇到了同样的问题,我知道已经有一段时间了......
    • 不行:for name, unbound_field in itertools.chain(fields, extra_fields): TypeError: 'NoneType' object is not iterable
    【解决方案3】:

    就我而言, 我使用了 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))
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-27
      • 1970-01-01
      • 1970-01-01
      • 2012-10-07
      相关资源
      最近更新 更多