4

我有一个表单,我必须验证然后将数据保存在数据库中。我有一个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)

现在上面的代码很愚蠢,因为我必须对视图中的每个字段名称进行硬编码。还有其他方法可以用表单字段填充模型的字段吗?谢谢

4

3 回答 3

8

您可以像这样使用 .populate_obj 方法:

if form.validate_on_submit():
    campaign = Campaign()
    form.populate_obj(campaign)

另请查看有关此的文档

于 2013-01-23T18:46:42.123 回答
4

sqlalachemy 有 wtforms 扩展:

还有一些东西可以帮助你

来自链接:

from flaskext.wtf import Form
from wtforms.ext.appengine.db import model_form
from models import MyModel

MyForm = model_form(MyModel, Form)
于 2013-01-23T14:13:16.493 回答
0

你也可以这样做:

if request.method == 'POST' and form.validate() == True:
    create new user

并将用户发送到所需的页面

于 2017-06-23T19:46:05.930 回答