Reputation: 5391
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
Upvotes: 4
Views: 7857
Reputation: 11
You can also do something like this:
if request.method == 'POST' and form.validate() == True:
create new user
and send the user to a desired page
Upvotes: 0
Reputation: 325
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.
Upvotes: 8
Reputation: 4910
there is wtforms extension for sqlalachemy:
also somethings can 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)
Upvotes: 4