Search code examples
pythonflaskflask-admin

Customize widget for a form in ModelView in flask-admin


I have a model News:

class News(db.Model):
    __tablename__ = 'news'
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String)
    active_from = db.Column(db.DateTime)
    active_until = db.Column(db.DateTime)

which gets integrated into flask-admin like so:

class MyModelView(ModelView):
    def is_accessible(self):
        return current_user.usergroup.name == 'admin'

admin.add_view(MyModelView(News, db.session))

but when I open my admin page I see an input type='text' widget for news.content. How can I put a textarea there instead?


Solution

  • In the code, db.String columns are mapped to StringFields, and db.Text columns are mapped to TextAreaFields, which present the user with text inputs and textareas, respectively.

    To overwrite this behavior, you can set the form_overrides field:

    from wtforms.fields import TextAreaField
    
    class MyModelView(ModelView):
        form_overrides = dict(string=TextAreaField)
        def is_accessible(self):
            return current_user.usergroup.name == 'admin'