我有一个表单,我必须验证然后将数据保存在数据库中。我有一个SQLAlchemy
名为的模型Campaign
,看起来像这样
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Campaign(db.Model):
__tablename__ = 'campaigns'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
priority = db.Column(db.SmallInteger)
starts_at = db.Column(db.Date)
ends_at = db.Column(db.Date)
.... bla bla bla
现在我有一个WTForm
这样的验证表格
from flask.ext.wtf import Form, TextField, IntegerField, DateField, Required, NumberRange
class CampaignForm(Form):
def date_validation(form, field):
#some validation on date
name = TextField(validators=[Required()])
priority = IntegerField(validators=[Required(), NumberRange(min=1,max=100)])
start_date = DateField(validators=[Required(), date_validation])
end_date = DateField(validators=[Required(), date_validation])
... bla bla bla
现在要验证和保存表单数据,我可以这样做是我的view
code in Flask
class CampaignsView(MethodView):
def post(self):
"""
For creating a new campaign
"""
form = CampaignForm(request.form)
if form.validate():
campaign = Campaign(form.name.data, form.priority.data, and so on )
session.add(campaign)
现在上面的代码很愚蠢,因为我必须对视图中的每个字段名称进行硬编码。还有其他方法可以用表单字段填充模型的字段吗?谢谢