[英]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.