WTForms の model_form を使えば一々フォームクラスを作らなくて良いが、各フィールドに対して独自の処理をしたい場合に困る。
例えば、特定のフィールドに対して別のバリデーションを追加したい場合や、エラーメッセージを変更したい場合。
そんな時は model_form の field_args にフィールドの情報を注入してやれば良いみたい。
Automatically create a WTForms Form from model | Flask (A Python Microframework)
#!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flask, render_template from flaskext.wtf import Form from wtforms.ext.sqlalchemy.orm import model_form from db import db_session from models import User app = Flask(__name__) @app.teardown_request def shutdown_session(exception=None): db_session.remove() @app.route('/') def index(): field_args = { 'name': { 'label': u'名前', 'validators' : [validators.Length(max=10)], } } UserForm = model_form(User, Form, field_args=field_args) form = UserForm() return render_template('index.html', form=form) if __name__ == '__main__': app.run(debug=True)
こんな感じで書いてやると、
<!DOCTYPE HTML> <html> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> <title>Sample</title> </head> <body> <div><label for="name">名前</label><input id="name" name="name" type="text" value="" /></div> <div><label for="email">Email</label><input id="email" name="email" type="text" value="" /></div> </body> </html>
というような結果になった。
自動生成するフォームに対して外部からいじる場合は、field_args に値を入れるとよいが、いじる場合はやはりちゃんとフォームクラスを作った方が良いような気がする。