Form validation with WTForms and SQLAlchemy autocomplete model with form data in Flask

I have a form that I have to validate and then save the data to a database. I have a model SQLAlchemy

called Campaign

that looks something like this:

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

      

Now I have a form WTForm

to validate as

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

      

Now, to validate and save the form data, I can do something like this: 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)

      

Now the above code is silly because I have to hard-code each field name in the view. Is there any other way where I can populate my model fields with form fields? Thanks to

+3


source to share


3 answers


You can use the .populate_obj method like this:

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

      



Also check out the docs .

+7


source


there is a wtforms extension for sqlalachemy:

can also help you



from links:

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

MyForm = model_form(MyModel, Form)

      

+3


source


You can also do something like this:

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

      

and send the user to the desired page

0


source







All Articles