WTForms 创建可变数量的字段 [英] WTForms create variable number of fields
问题描述
如何动态创建一些具有不同问题但答案相同的表单字段?
from wtforms import Form, RadioFieldfrom wtforms.validators import 必需类变量形式(形式):def __init__(formdata=None, obj=None, prefix='', **kwargs):super(VariableForm, self).__init__(formdata, obj, prefix, **kwargs)问题 = kwargs['问题']//如何动态创建三个格式如下的问题?问题 = RadioField(# 题 ?,[必需的()],选择 = [('是', '是'), ('否', '否')],)问题=(你喜欢豌豆吗?",你喜欢茶吗?",你好吗?")形式 = VariableForm(问题 = 问题)
a> 一直以来.
def my_view():F类(MyBaseForm):经过F.username = TextField('用户名')对于 iterate_some_model_dynamically() 中的名称:setattr(F, name, TextField(name.title()))表单 = F(request.POST, ...)# 查看东西
我没有意识到的是,必须在任何实例化发生之前设置类属性.清晰度来自这个 bitbucket 评论:
<块引用>这不是错误,而是设计使然.有很多问题向实例化表单添加字段 - 例如,数据进来通过 Form 构造函数.
如果您重新阅读链接的线程,您会注意到您需要派生类,向其添加字段,然后实例化新类.通常,您会在视图处理程序中执行此操作.
How I would dynamically create a few form fields with different questions, but the same answers?
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)
It was in the docs all along.
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
What I didn't realize is that the class attributes must be set before any instantiation occurs. The clarity comes from this 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.
这篇关于WTForms 创建可变数量的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!