0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

FlaskFormで、formを動的に生成する

Posted at

FlaskFormはイロイロ便利ではありますが、もう少し柔軟に使えないかなぁ・・・と、お悩みのあなたに。

普通は、こんな感じで事前に定義しておきます。

from flask_wtf import FlaskForm
from wtforms import StringField

class EventForm(FlaskForm):
    name = StringField('Event Title')

form = EventForm()

これを動的に生成する方法を考えてみました。

メリット
・Viewを共通化できます。
・Formクラスの生成をカスタマイズできます。
・FlaskFormの利便性を、そのまま享受できます。

まず、設定情報を作ります。

form_conf = {
    'Event': {
        'name': StringField('Event Title')
    }
}

次にクラスを定義します。

class ExForm:
    def __new__(cls, kind):
        field_dict = model_conf[kind]
        return type(kind, (FlaskForm,), field_dict)

そして、formを生成します。

kind = 'Event'
F = ExForm(kind)
form = F()

あとは、お好きにどうぞ。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?