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

Creating custom fields and validation


Apart from providing a bunch of fields and validations, Flask also provides the flexibility to create custom fields and validations. Sometimes, we might need to parse some form of data that cannot be processed using the available current fields. In such cases, we can implement our own fields.

How to do it…

In our catalog application, we used SelectField for the category, and we populated the values for this field in our create_product() method on a GET request. It would be much more convenient if we did not bother about this and the population of this field was taken care of by itself. Let's implement a custom field for this in models.py:

class CategoryField(SelectField):

    def iter_choices(self):
        categories = [(c.id, c.name) for c in Category.query.all()]
        for value, label in categories:
            yield (value, label, self.coerce(value) == self.data)

    def pre_validate(self, form):
        for v, _ in [(c.id, c.name) for c in Category...