Search code examples
pythonflaskflask-sqlalchemyflask-admin

How can I turn a string model field into a select input in Flask-Admin?


I have a string field in my SQLAlchemy model and I would like to expose a select box with a few options in Flask-Admin instead of the standard text field.

class MyModel(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    my_field = db.Column(db.String(128))  # Field I would like to be choices


class MyModelView(ModelView):
    """
    Admin manager for MyModel
    """

    # Which option should I use here?

    def __init__(self):
        super(MyModelView, self).__init__(MyModel, db.session)

Solution

  • You achieve this functionality by using 'form_choices' in the model view as the following example based on the code embedded in your question illustrates:

       class MyModel(db.Model):
           id = db.Column(db.Integer, primary_key=True)
           my_field = db.Column(db.String(128))  # Field I would like to be choices
    
    
        class MyModelView(ModelView):
            """
            Admin manager for MyModel
            """
    
                form_choices = {
                     'my_field': [
                         ('choice_1', 'Choice 1'),
                         ('choice_2', 'Choice 2'),
                         ('choice_3', 'Choice 3'),
                         ('choice_4', 'Choice 4'),
                         ('choice_5', 'Choice 5')
                    ]
               }
    
            def __init__(self):
                super(MyModelView, self).__init__(MyModel, db.session)
    

    Reference:

    Flask-Admin documentation:

    You can restrict the possible values for a text-field by specifying a list of select choices:

    form_choices = { 'title': [ ('MR', 'Mr'), ('MRS', 'Mrs'), ('MS', 'Ms'), ('DR', 'Dr'), ('PROF', 'Prof.') ] }