2017-01-20 45 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