I have a form that i have to validate and then save the data in the database. I have a SQLAlchemy
model called Campaign
which 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 WTForm
form for validation like this
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 is my 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 stupid because i have to hard-code every field name in the view. Is there some other way where i can fill the fields of my model with form fields? Thanks
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 on this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With