简体   繁体   English

Flask-WTF 实例化嵌套 Forms

[英]Flask-WTF Instantiate nested Forms

i have nested Forms similar to this:我已经嵌套了类似于此的 Forms:

class PhoneForm(FlaskForm):
    number = StringField('Phone Number')
    valid_since = None

class AdressForm(FlaskForm):
    phone_number = FormField(PhoneForm)
    city = SelectForm('City')
    name = StringField('Name')

I have fiddled around for hours now and i can't find a way to instatiate the forms as i want them.我现在已经摆弄了几个小时,但我找不到一种方法来按照我的需要设置 forms。 I've tried overriding the constructor and with a static method我尝试使用 static 方法覆盖构造函数

def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.name.data = 'Kevin123'
        self.phone_number = PhoneForm()

    @staticmethod
    def create_form():
        form = AdressForm()
        form.name.data = 'Kevin'
        form.phone_number = PhoneNumber.create_form()  # calls the creator method of the other form
        return form

My actual app is a lot larger than this, so i need a way to create Forms by themselves (to set data or choices for select-field) and then add them into the nested form.我的实际应用程序比这大得多,所以我需要一种方法来自己创建 Forms(为选择字段设置数据或选项),然后将它们添加到嵌套表单中。

From what I've read the only way to pass data into a form in Flask-WTF is by doing: form = AdressForm(phone_number='123456') .从我读到的将数据传递到 Flask-WTF 中的表单的唯一方法是: form = AdressForm(phone_number='123456') Nothing else really works or makes the form "unsubmittable" (ie the data doesent change after submitting.没有其他方法真正起作用或使表单“不可提交”(即提交后数据不会发生变化。

Is there a way to do this in Flask-WTF or do i have to try it with regular WTforms.有没有办法在 Flask-WTF 中做到这一点,或者我必须用常规的 WTforms 尝试它。

Thanks:)谢谢:)

If I understand your situation, I think you need drop the init stuff.如果我了解您的情况,我认为您需要删除 init 内容。 Here is some code for your handler (The Python method that interacts with the form):这是您的处理程序的一些代码(与表单交互的 Python 方法):

@app.route('/adress', methods=['GET', 'POST'])
def data():
    form = forms.AdressForm()
    form.phone_number.number.data = '888.888.8888'
    form.phone_number.valid_since.data = '1984'

Does that get you started?这会让你开始吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM