【问题标题】:Passing arguments to form constructors, WTForms将参数传递给表单构造函数,WTForms
【发布时间】:2016-03-12 01:12:07
【问题描述】:

可能重复:WTForms - dynamic labels by passing argument to constructor?

我正在使用 WTForms 和 Flask 创建一个允许用户输入新联系人的表单:

class ContactForm(Form):
    firstName = StringField("First Name", [validators.Required("Please enter your first name.")])
    lastName = StringField("Last Name", [validators.Required("Please enter your last name.")])
    email = StringField('Email')
    phoneNo = StringField('Phone #')
    notes = StringField('Notes', widget=TextArea())
    submit = SubmitField("Create Contact")

    def __init__(self, *args, **kwargs):
        Form.__init__(self, *args, **kwargs)

我想在用户创建新联系人以及用户想要编辑现有联系人时使用此表单,因此我需要能够动态更改向用户显示的一些标签(在特别是我需要更改提交按钮上的文本)。为此,我想将一个字符串传递给构造函数,但我对 Python 或 WTForms 都不熟悉。有人可以帮我弄清楚怎么做吗?

【问题讨论】:

    标签: python flask wtforms


    【解决方案1】:

    我现在正在做类似的事情。我想知道你的 HTML 模板是什么样的。我用我的模板来担心提交按钮的文本。这是 init.py 中的类 >>>

    from flask import Flask, render_template
    from wtforms import Form, StringField, validators
    class InputForm(Form):
        something = StringField(u'Enter a website', [validators.required(), validators.url()])
    @app.route('/somewhere/', methods=['GET', 'POST'])
    def index():
      form = InputForm(request.form)
      if request.method == 'POST' and form.validate():
        url = form.something.data
        someAction = compute(url)
        return render_template("view_output.html", form=form, someAction = someAction)
      else:
        return render_template("view_input.html", form=form)
    

    这是我在模板中利用它的方式>>>

    <form method=post action="">
        <div class="form-group">
            <label for="thaturl">Website Adress</label>
            {{ form.something(style="margin-top: 5px; margin-bottom: 5px; height: 26px; width: 292px; margin-right: 15px;") }}
        </div>
        <button type="submit" class="btn btn-primary" aria-label="Left Align" style="margin-top: 5px; margin-bottom: 5px; height: 44px; margin-right: 15px">
            <span class="glyphicon glyphicon-signal" aria-hidden="true"></span>
            Check My Site
        </button>
        </form>
    

    【讨论】:

    • 使按钮成为模板的一部分会起作用,问题是按钮是联系表单本身的一部分。为了让它出现在我的模板中,我所做的就是写{{ form.submit }}。我最终所做的只是编写另一个模板,但这样做涉及大量复制/粘贴,这绝不是一件好事。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2015-10-11
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多