limit choices with dropdown in flask-admin
Asked Answered
T

1

17

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.

Trivalent answered 19/8, 2015 at 22:55 Comment(0)
D
32

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.

Drud answered 20/8, 2015 at 4:2 Comment(4)
Choice "A" was originally used, although it creates a multitude of nightmares (as you mentioned). So, I modified it to a string field and restrict the entries in the controllers.Trivalent
Yeah, there's a time and place for enum. Storage is smaller with enum (only one copy of the value), but lookup / joining can be slower (discussed on pp.123-124 of High-Performance MySQL, 3rd ed. It's a good question, hope it will be helpful to others. :)Drud
By the way there seems to be a bug with enum fields in flask-admin which may be what you were experiencing. At the moment flask-admin seems to have a lot of unresolved issues which are not so minor (see the Security thing #1000 and others). You'd think that by 2015 the problem of creating admin interfaces would be solved, but not at all. I haven't found the silver bullet apart from taking the time to code the whole thing by hand, which also lets me avoid the terribly inefficient ORMDrud
use form_choices and column_choices together, would be betterChromolithograph

© 2022 - 2024 — McMap. All rights reserved.