我有一个User
模型类,password
是其中一个属性。我正在使用Flask Web框架和Flask-Admin扩展来创建我的模型类的管理视图。我想在管理视图中创建某些字段,例如password
不可编辑或根本不显示它们。我该怎么做?
我可以使字段不显示在普通视图中,但是当我点击表格中任何记录的编辑按钮时,所有字段都会显示并且可以编辑。
答案 0 :(得分:16)
您应该从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
},
}
希望这有帮助! 有关更多信息,请查看文档:
答案 1 :(得分:6)
这是一个扩展了Remo答案和so answer的解决方案。它允许使用不同的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
]
答案 2 :(得分:1)
解决问题的另一种方法是使用名为on_form_prefill
的Flask-Admin ModelView方法来设置readonly属性参数。根据{{3}}:
on_form_prefill (表单,ID)
执行其他操作以预先填写编辑表单。
从edit_view调用,如果当前操作正在渲染表单而不是接收客户端输入,则在执行默认预填充后。
换句话说,这是一个触发器,仅在打开编辑表单时运行,不创建一个。
因此,上面使用的示例的解决方案是:
class UserView(ModelView):
...
def on_form_prefill(self, form, id):
form.name.render_kw = {'readonly': True}
该方法在应用所有其他规则后运行,因此它们都不会被破坏,包括列集。