14

How can I make a field on a ModelView readonly?

class MyModelView(BaseModelView):
    column_list = ('name', 'last_name', 'email')
nsfyn55
  • 14,875
  • 8
  • 50
  • 77
user2071987
  • 213
  • 1
  • 3
  • 8

5 Answers5

21

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
        }
    }
nsfyn55
  • 14,875
  • 8
  • 50
  • 77
Richard Aplin
  • 262
  • 2
  • 6
  • 15
    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). – booshong May 15 '15 at 23:02
12

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)
brab
  • 121
  • 1
  • 2
  • Is there any way to set it vai the follow? form_widget_args = { 'type_values': { 'readonly': 'readonly' } } – Lawrence Liu Jun 18 '15 at 05:43
  • 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. – pip Jun 18 '15 at 09:39
  • i.e. form_overrides = dict(your_field_name=ReadonlyTextField) or possibly form_extra_fields = dict(your_field_name=ReadonlyTextField('Label',...)) – pip Jun 18 '15 at 09:40
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
        }
    }
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
MF DOOM
  • 413
  • 4
  • 19
7

try this:

class DisabledTextField(TextField):
  def __call__(self, *args, **kwargs):
    kwargs.setdefault('disabled', True)
    return super(DisabledTextField, self).__call__(*args, **kwargs)
thkang
  • 11,215
  • 14
  • 67
  • 83
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>
Doobeh
  • 9,280
  • 39
  • 32