这是我在简单的Flask WTForms示例中的代码。我一直在努力学习如何让ModelForms进行验证。验证与标准表单一起使用没问题。对我所做错的任何帮助都表示赞赏。
from flask.ext.wtf import Form
from wtforms_alchemy import model_form_factory
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(128), nullable=False, unique=True)
username = db.Column(db.String(32), nullable=False, unique=True)
BaseModelForm = model_form_factory(Form)
class ModelForm(BaseModelForm):
@classmethod
def get_session(cls):
return db.session
class UserForm(ModelForm):
class Meta:
model = User
flask_shell >> uf = UserForm(obj=jeff, csrf_enabled=False)
flask_shell >> uf.validate() #False
flask_shell >> uf.errors
{'email': ['This field is required.'],
'password_hash': ['This field is required.'],
'username': ['This field is required.']}
flask_shell >> uf.__dict__
{'SECRET_KEY': '',
'_errors': None,
'_fields': OrderedDict([('csrf_token',
<wtforms.ext.csrf.fields.CSRFTokenField at 0x1075239e8>),
('email',
<wtforms_components.fields.html5.StringField at 0x107523ac8>),
('username',
<wtforms_components.fields.html5.StringField at 0x107523b70>),
'_obj': <User 'jeff'>,
'_prefix': '',
'csrf_enabled': False,
'csrf_token': <wtforms.ext.csrf.fields.CSRFTokenField at 0x1075239e8>,
'email': <wtforms_components.fields.html5.StringField at 0x107523ac8>,
'meta': <wtforms.form.Meta at 0x107523898>,
'username': <wtforms_components.fields.html5.StringField at 0x107523b70>}