Book Image

Flask Framework Cookbook

By : Shalabh Aggarwal
Book Image

Flask Framework Cookbook

By: Shalabh Aggarwal

Overview of this book

Table of Contents (19 chapters)
Flask Framework Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

SQLAlchemy model data as form representation


First, let's build a form using a SQLAlchemy model. We will take the product model from our catalog application and add the functionality to create products from the frontend using a webform.

Getting ready

We will use our catalog application from Chapter 4, Working with Views. We will develop a form for the Product model.

How to do it…

To remind you, the Product model looks like the following lines of code in the models.py file:

class Product(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255))
    price = db.Column(db.Float)
    category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
    category = db.relationship(
        'Category', backref=db.backref('products', lazy='dynamic')
    )
    company = db.Column(db.String(100))

First, we will create a ProductForm class; this will subclass the Form class, which is provided by flask_wtf, to represent the fields needed on a webform:

from flask_wtf import...