2016-03-12 33 views
0

可能重复:WTForms - dynamic labels by passing argument to constructor?参数传递到形式构造,WTForms

我创建使用WTForms和瓶,让用户进入一个新的接触形式:

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。有人可以帮我弄清楚如何做到这一点?

回答

0

我正在做类似的事情。我想知道你的HTML模板是什么样子的。我用我的模板来担心提交按钮文本。这里是初始化的.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> 
+0

制作模板的按键部分会工作,问题在类该按钮是联系人表单本身的一部分。为了让它在我的模板中显示,我所做的就是编写'{{form.submit}}'。我最终做的只是写另一个模板,但这样做涉及到很多复制/粘贴,这绝不是一件好事。 – Adam