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

There's more...

We just saw how to write custom fields. Similarly, we can write custom validations, too. Let's assume that we do not want to allow duplicate categories. We can implement this in our models easily, but let's do this using a custom validator on our form:

from wtforms.validators import ValidationError def check_duplicate_category(case_sensitive=True): def _check_duplicate(form, field): if case_sensitive: res = Category.query.filter( Category.name.like('%' + field.data + '%') ).first() else: res = Category.query.filter( Category.name.ilike('%' + field.data + '%') ).first() if res: raise ValidationError( 'Category named %s already exists' % field.data ) return _check_duplicate class CategoryForm(NameForm): name = StringField('Name', ...
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