Readonly text field in Flask-Admin ModelView
Asked Answered
M

5

14

How can I make a field on a ModelView readonly?

class MyModelView(BaseModelView):
    column_list = ('name', 'last_name', 'email')
Mussman answered 14/2, 2013 at 12:25 Comment(0)
P
20

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
        }
    }
Palmer answered 17/9, 2013 at 0:40 Comment(1)
This might not be what you want. I implemented this but noticed that the fields that were disabled were getting cleared on submission. When I used readonly instead, then I got the expected behavior (value doesn't change).Achitophel
I
11

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)
Ignacioignacius answered 30/5, 2014 at 16:38 Comment(3)
Is there any way to set it vai the follow? form_widget_args = { 'type_values': { 'readonly': 'readonly' } }Selfcontrol
Lawrence, I would specify form_extra_fields as the same name as the field you want to be readOnly and it will override this field.Throaty
i.e. form_overrides = dict(your_field_name=ReadonlyTextField) or possibly form_extra_fields = dict(your_field_name=ReadonlyTextField('Label',...))Throaty
R
8

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
        }
    }
Romanticist answered 11/8, 2017 at 13:10 Comment(0)
T
7

try this:

class DisabledTextField(TextField):
  def __call__(self, *args, **kwargs):
    kwargs.setdefault('disabled', True)
    return super(DisabledTextField, self).__call__(*args, **kwargs)
Torrence answered 7/3, 2013 at 9:51 Comment(0)
E
6

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>
Emanuel answered 14/2, 2013 at 13:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.