gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:03:15 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com