As you already noticed, the readonly property for a field is pretty simple , but making it dynamic is a bit tricky.
First of all, you need a custom field class:
from wtforms.fields import StringField class ReadOnlyStringField(StringField): @staticmethod def readonly_condition():
Set form_overrides for your view:
class ProjectView(sqla.ModelView): form_overrides = { 'project_name': ReadOnlyStringField }
You need to pass the custom function readonly_condition to the ReadOnlyStringField instance. The easiest way I've found is to override the edit_form method:
class ProjectView(sqla.ModelView): def edit_form(self, obj=None): def readonly_condition(): if obj is None: return False return obj.approve form = super(ProjectView, self).edit_form(obj) form.project_name.readonly_condition = readonly_condition return form
Happy coding!
source share