Readonly text field in Flask-Admin ModelView

风流意气都作罢 提交于 2019-11-28 02:58:12

问题


How can I make a field on a ModelView readonly?

class MyModelView(BaseModelView):
    column_list = ('name', 'last_name', 'email')

回答1:


If you're talking about Flask-Admin with SQLAlchemy Models, and you're declaring a view by inheriting from sqlamodel.ModelView, you can just add this to your class definition:

class MyModelView(BaseModelView):
    column_list = ('name', 'last_name', 'email')
    form_widget_args = {
        'email':{
            'disabled':True
        }
    }



回答2:


I don't have enough reputation to comment on @thkang's answer, which is very close to what worked for me. The disabled attribute excludes the field from the POST data, but using readonly had the desired effect.

from wtforms.fields import TextField

class ReadonlyTextField(TextField):
  def __call__(self, *args, **kwargs):
    kwargs.setdefault('readonly', True)
    return super(ReadonlyTextField, self).__call__(*args, **kwargs)



回答3:


try this:

class DisabledTextField(TextField):
  def __call__(self, *args, **kwargs):
    kwargs.setdefault('disabled', True)
    return super(DisabledTextField, self).__call__(*args, **kwargs)



回答4:


I got weird errors when I tried to use disabled for text fields, so I used readonly instead:

class MyModelView(BaseModelView):
    column_list = ('name', 'last_name', 'email')
    form_widget_args = {
        'email':{
            'readonly':True
        }
    }



回答5:


When you are rendering the field in your Jinja template, just pass in disabled=true if WTForms doesn't recognise the kwarg, it just passes it to be an attribute to the html element.

<form>
{{ form.example(disabled=True) }}
</form>


来源:https://stackoverflow.com/questions/14874846/readonly-text-field-in-flask-admin-modelview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!