Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 820
lovesh Avatar asked Dec 15 '22 15:12

lovesh


1 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 on this.

like image 78
Alexander Jung-Loddenkemper Avatar answered Dec 21 '22 09:12

Alexander Jung-Loddenkemper