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
there is a wtforms extension for sqlalachemy:
- WTForms Documentation -> http://wtforms.simplecodes.com/docs/0.6.1/ext.html#module-wtforms.ext.sqlalchemy
can also help you
- kvesteri / wtforms-alchemy GitHub → https://github.com/kvesteri/wtforms-alchemy
- Automatic creation of a WTForms form from a model | Checkbox (A Python Micrograph) → http://flask.pocoo.org/snippets/60/
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 to share