Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

limit choices with dropdown in flask-admin

My SQLAlchemy model has a String field that I would like to limit to a few choices.

I am wondering how I would be able to create a dropdown for this field in the Flask-Admin interface that would ensure that the db is only populated with one of my choices. If I let the user manually enter these fields, they may spell them incorrectly, etc.

like image 859
Brian Leach Avatar asked Aug 19 '15 22:08

Brian Leach


1 Answers

enum, form_choices and form_args

Your question is about restricting values at the form level, but we can also briefly discuss it at the schema level.

A. Restricting Values at the Database Level: enum fields

To limit the range of allowable values, the first thing to consider is whether you might like the database to enforce that for you. Most databases have an enum type field that allow you to restrict a field to a set of values (MySQL, PostGres). This approach has pros and cons. Among the cons, the values may not be listed in the order you expect; and each time you want to introduce new values to the set, you have to modify the database.

B. Restricting Values with drop-downs: form_choices

To create drop-downs that present a set of allowable values, create a customized ModelView and define your range of values in form_choices. For instance:

class FilmAdmin(sqla.ModelView):

    form_choices = { 'now_showing': [ ('0', 'Not Showing'), ('1', 'Showing')],
                     'color': [('bw', 'Black & White'), ('color', 'Color')]
                   }

    # (many other customizations can go here)

In form_choices, you have created drop-downs for two fields: now_showing and color. The first field admits the values 0 and 1, but to make it easier on the eyes the form will show Not Showing for 0 and Showing for 1.

Note that this will work in a regular form, but not in an inline form.

You will need to add the ModelView to the app: something like

admin.add_view(FilmAdmin(yourmodels.Film, db.session))

C. Validation: form_args

In inline forms, you may not have the drop-down. But you can keep refining your custom ModelView by defining WTF validators for various fields.

As we did with form_choices, you can define a form_args dictionary containing a validators list. For instance:

# first import the `AnyOf` validator: 
from wtforms.validators import AnyOf

class FilmAdmin(sqla.ModelView):

    # column_exclude_list = ...
    # form_excluded_columns = ...
    # form_choices = ...

    form_args = {
        'flavors': {
            'validators': [AnyOf(['strawberry', 'chocolate'])]
        }
    }

There are many pre-defined validators, and you can define your own: please refer to the flask-admin introduction and to the validators section of the WTF documentation.

like image 131
zx81 Avatar answered Nov 10 '22 09:11

zx81