4

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

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

That's great. And is there any way to avoid generating the same logical class once for the form, and once for the database? Can one generate one class for both?
@famargar not sure whether I understand your question?
4

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)

2 Comments

In (this)[flask.pocoo.org/snippets/60/] approach i have to pass validators in the field_args argument of model_form. Cant i use my form class CampaignForm?
@lovesh no, you can extend data with field_args.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.