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

I have a string field in my SQLAlchemy model and I would like to open a select box with multiple options in Flask-Admin instead of a standard textbox.

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)

      

+3


source to share


2 answers


In the end, it was a combination of form_overrides

and form_args

. form_overrides

instructs the form to use the select box, and form_args

allows you to pass options and other parameters.



class MyModel(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    my_field = db.Column(db.String(128))


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

    form_overrides = dict(
        my_field=SelectField
    )
    form_args = dict(
        my_field=dict(
            choices=[
                ('choice_1', 'Choice 1'),
                ('choice_2', 'Choice 2')
            ]
        )
    )
    def __init__(self):
        super(MyModelView, self).__init__(MyModel, db.session)

      

+3


source


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 limit the possible values ​​for a text box by specifying a list of favorites:

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

+1


source







All Articles