2017-01-20 75 views
-1

我嘗試使用模塊WTForms在Flask中創建一個Form,問題是我需要創建一個構造函數來初始化一些用於Form的變量。在wtforms中實現__init__,Flask

的代碼是下一個:

startup.py

@app.route("/startup/new", methods=["GET"]) 
def formNewStartUp(): 

    newForm = NewStartUpForm(request.form) 

    return render_template("platform/startup/new.html", newForm=newForm.getForm()) 

newStartUpForm.py

class NewStartUpForm(Form): 

    # Constructor 
    def __init__(self, *arg, **kwarg): 
     self.aCategories = StartupCategories() # Another class 
     self.lang = getUserLanguage(request) # Language 

    def getForm(self, *arg, **kwarg): 

     # Detail Main 
     titleStartup = TextField() 
     webStartup = TextField() 
     groupStartUp = SelectField('Groups') 
     categoryStartUp = SelectField('Categories', choices=self.aCategories.getAllCategoriesByLang(self.lang)) 
     shortDescription = TextAreaField() 

初始化我打電話到 「getForm()」 函數對象之後加載表單,但是當我在HTML端輸出是「無」。

我用什麼壞?

回答

1

這是正常的你沒有得到,因爲get_form()方法不返回任何東西。像下面的東西應該爲你工作:

class NewStartUpForm(Form): 
    def __init__(self, *arg, **kwarg): 
     self.aCategories = StartupCategories() 
     self.lang = getUserLanguage(request) 
    def getForm(self, *arg, **kwarg): 
     choices=self.aCategories.getAllCategoriesByLang(self.lang) 
     return SecondForm(choices) 

class SecondForm(Form): 
    titleStartup = TextField() 
    webStartup = TextField() 
    groupStartUp = SelectField('Groups') 
    categoryStartUp = SelectField('Categories') 
    shortDescription = TextAreaField() 
    def __init__(self, choices, *args, **kwargs): 
     super(SecondForm, self).__init__(*args, **kwargs) 
     self.categoryStartUp.choices = choices