【问题标题】:Implement __init__ in wtforms, Flask在 wtforms、Flask 中实现 __init__
【发布时间】:2017-01-20 18:34:35
【问题描述】:

我尝试使用模块 WTForms 在 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 端时,输出为“无”。

我用什么不好?

【问题讨论】:

    标签: python object flask init wtforms


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多