我有一个使用枚举定义访问级别的模型,如下所示:
class DevelModelView(ModelView):
edit_modal = True
def is_accessible(self):
return current_user.is_authenticated and current_user.access is AccessLevel.DEVEL
class DevelStaffModelView(DevelModelView):
column_editable_list = ['access']
column_filters = ['access']
column_searchable_list = ['login', 'email']
form_choices = {'access': [(AccessLevel.DEVEL.name, AccessLevel.DEVEL.value),
(AccessLevel.ADMIN.name, AccessLevel.ADMIN.value),
(AccessLevel.STAFF.name, AccessLevel.STAFF.value)]}
枚举定义如下...
class AccessLevel(Enum):
DEVEL = 'Developer'
ADMIN = 'Administrator'
STAFF = 'Staff Member'
使用form_choices属性,我能够以值形式(IE:开发人员)在模式和可编辑列选择中显示,但不幸的是,显示仍使用名称(IE:名称)。
为澄清起见,我本质上是在询问是否有Flask Admin在显示表中默认显示一个枚举值而不是名称。预先谢谢你...
还提供Staff模型,以防万一。。。
class Staff(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
login = db.Column(db.String(64), unique=True)
_password = db.Column(db.String(128))
email = db.Column(db.String(100))
access = db.Column('access', db.Enum(AccessLevel))
@hybrid_property
def password(self):
return self._password
@password.setter
def password(self, plaintext):
self._password = bcrypt.generate_password_hash(plaintext)
def check_password(self, plaintext):
return bcrypt.check_password_hash(self._password, plaintext)
def __str__(self):
return "%s: %s (%s)" % (self.access.name, self.login, self.email)
答案 0 :(得分:1)
您需要column_formatters功能才能在表中显示正确的值。格式化程序功能的定义如下:
def access_level_formatter(view, context, model, name):
db_value = getattr(model, name)
enum_value = getattr(AccessLevel, db_value)
return enum_value.value
并且您需要在用于access
列的视图类中指定此格式化程序:
class DevelStaffModelView(DevelModelView):
column_formatters = {
'access': access_level_formatter,
}
答案 1 :(得分:1)
如果要显示几种enum
类型,而不是创建单个column_formatters
,则可以更新Flask-Admin使用的column_type_formatters。
示例
from flask_admin.model import typefmt
class AccessLevel(Enum):
DEVEL = 'Developer'
ADMIN = 'Administrator'
STAFF = 'Staff Member'
# ...
MY_DEFAULT_FORMATTERS = dict(typefmt.BASE_FORMATTERS)
MY_DEFAULT_FORMATTERS.update({
AccessLevel: lambda view, access_level_enum: access_level_enum.value # could use a function here
})
class DevelModelView(ModelView):
column_type_formatters = MY_DEFAULT_FORMATTERS
# ...
也请考虑按照此SO answer中的说明设置AccessLevel选项。这意味着您不必在模型视图定义中重复枚举名称/值。请注意__str__
类中的__html__
和AccessLevel
方法。
示例
from flask_admin.model import typefmt
from wtforms import SelectField
class AccessLevel(Enum):
DEVEL = 'Developer'
ADMIN = 'Administrator'
STAFF = 'Staff Member'
def __str__(self):
return self.name # value string
def __html__(self):
return self.value # option labels
def enum_field_options(enum):
"""Produce WTForm Field instance configuration options for an Enum
Returns a dictionary with 'choices' and 'coerce' keys, use this as
**enum_fields_options(EnumClass) when constructing a field:
enum_selection = SelectField("Enum Selection", **enum_field_options(EnumClass))
Labels are produced from enum_instance.__html__() or
str(eum_instance), value strings with str(enum_instance).
"""
assert not {'__str__', '__html__'}.isdisjoint(vars(enum)), (
"The {!r} enum class does not implement a __str__ or __html__ method")
def coerce(name):
if isinstance(name, enum):
# already coerced to instance of this enum
return name
try:
return enum[name]
except KeyError:
raise ValueError(name)
return dict(choices=[(v, v) for v in enum], coerce=coerce)
class DevelModelView(ModelView):
column_type_formatters = MY_DEFAULT_FORMATTERS
# ...
form_overrides = {
'access': SelectField,
}
form_args = {
'access': enum_field_options(AccessLevel),
}
# ...