2016-03-12 34 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