python - WTForms 创建可变数量的字段

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

最佳答案

它是 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 :

This is not a bug, it is by design. There are a lot of problems with adding fields to instantiated forms - For example, data comes in through the Form constructor.

If you reread the thread you link, you'll notice you need to derive the class, add fields to that, and then instantiate the new class. Typically you'll do this inside your view handler.

关于python - WTForms 创建可变数量的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11622592/

相关文章:

python - Rest框架如何创建可选的嵌套对象?

validation - 代码架构 - Flask - 在哪里放置数据库中的表单验证?

python - Flask wtf 表单 AttributeError : 'Request' object has no attribute 'POST'

rest - 从同一服务器调用 REST API

Python在数据框中扩展网络地址

python - django 模型类是单例/仅实现一次吗?

python - 无法删除sqlite数据库

Wtforms表单域文本放大

python - 如何在 WTForms RadioField 中动态设置默认值?

python - 在不同的目录中创建一个 excel 文件