Skip to Content
Flask Framework Cookbook - Second Edition
book

Flask Framework Cookbook - Second Edition

by Shalabh Aggarwal
July 2019
Beginner to intermediate
302 pages
9h 38m
English
Packt Publishing
Content preview from Flask Framework Cookbook - Second Edition

How to do it...

In our catalog application, we used SelectField for 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 concern ourselves with this and the population of this field was taken care of by itself.

Now, let's implement a custom field to do 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.query.all()]: if self.data == v: break else: raise ValueError(self.gettext('Not a valid choice')) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Writing a Web Application with Flask

Writing a Web Application with Flask

Doug Farrell
Mastering Flask

Mastering Flask

Jack Stouffer

Publisher Resources

ISBN: 9781789951295Supplemental Content