[英]How to make a field non-editable in Flask Admin view of a model class
我有一个User
模型类, password
是许多中的一个属性。 我正在使用Flask Web框架和Flask-Admin扩展来创建我的模型类的管理视图。 我想在管理视图中创建某些字段,例如password
不可编辑或根本不显示它们。 我该怎么做?
我可以使字段不显示在普通视图中,但是当我单击表格中任何记录的编辑按钮时,所有字段都会显示并且可以编辑。
您应该从ModelView扩展视图并覆盖必要的字段。
在我的课堂上,它看起来像这样:
class UserView(ModelView):
column_list = ('first_name', 'last_name', 'username', 'email')
searchable_columns = ('username', 'email')
# this is to exclude the password field from list_view:
excluded_list_columns = ['password']
can_create = True
can_delete = False
# If you want to make them not editable in form view: use this piece:
form_widget_args = {
'name': {
'readonly': True
},
}
希望这可以帮助! 有关更多信息,请查看文档:
这是一个解决方案,扩展了雷莫的答案和这个答案 。 它允许使用不同的field_args进行编辑和创建表单。
from flask_admin.form.rules import Field
class CustomizableField(Field):
def __init__(self, field_name, render_field='lib.render_field', field_args={}):
super(CustomizableField, self).__init__(field_name, render_field)
self.extra_field_args = field_args
def __call__(self, form, form_opts=None, field_args={}):
field_args.update(self.extra_field_args)
return super(CustomizableField, self).__call__(form, form_opts, field_args)
class UserView(ModelView):
column_list = ('first_name', 'last_name', 'username', 'email')
searchable_columns = ('username', 'email')
# this is to exclude the password field from list_view:
excluded_list_columns = ['password']
can_create = True
can_delete = False
# If you want to make them not editable in form view: use this piece:
form_edit_rules = [
CustomizableField('name', field_args={
'readonly': True
}),
# ... place other rules here
]
另一种解决问题的方法是使用名为on_form_prefill
Flask-Admin on_form_prefill
方法来设置readonly属性参数。 据Flask-Admin Docs说 :
on_form_prefill (form,id)
执行其他操作以预填充编辑表单。
从edit_view调用,如果当前操作正在呈现表单而不是接收客户端输入,则在执行默认预填充之后。
换句话说,这是一个触发器,仅在打开编辑表单而不是创建表单时运行。
因此,上面使用的示例的解决方案将是:
class UserView(ModelView):
...
def on_form_prefill(self, form, id):
form.name.render_kw = {'readonly': True}
该方法在应用所有其他规则后运行,因此它们都不会被破坏,包括列集。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.