Closed OpenSourceSimon closed 3 months ago
Finally found a solution after months:
Variable = Base.classes.variables
class VariableView(ModelView):
list_columns = ["variable", "value"]
form_columns = ["variable", "value"]
column_default_sort = ("variable", False)
column_filters = ["variable"]
column_sortable_list = ["variable"]
column_searchable_list = ["variable"]
column_formatters = {
"variable": lambda view, context, model, name: model.variable.replace(
"_", " "
).capitalize(),
}
def edit_form(self, obj):
class VariableForm(FlaskForm):
pass
setattr(
VariableForm,
"variable",
StringField("Variable", validators=[Optional()], default=obj.variable),
)
try:
json_data = json.loads(obj.value)
for key in json_data:
setattr(
VariableForm,
key,
StringField(
key.capitalize(),
validators=[Optional()],
default=json_data[key],
),
)
except json.decoder.JSONDecodeError:
setattr(
VariableForm,
"Value",
StringField("Label", validators=[Optional()], default=obj.value),
)
return VariableForm(obj=obj)
def on_model_change(self, form, model, is_created):
# Update the model with the data from the form
json_output = {}
for field in form:
if field.name == "value":
return model
if field.name != "variable" and field.name != "csrf_token":
json_output[field.name] = field.data
model.value = json.dumps(json_output)
return model
admin.add_view(VariableView(Variable, user.session, name="Variables"))
Hey GitHub community š, I'm encountering an issue with rendering Flask-Admin edit form fields for variables stored as JSON in a PostgreSQL database. I have a table called
variables
where each row represents a variable, and its attributes are stored as JSON in thelabel
column. I'm using Flask-Admin to provide an interface for users to edit these variables.{"name": "Name", "email": "test@example.com"}
{"region": "Europe", "name": "DHL", "color": "blue"}
Here's many of the versions of code I've tried:
The
VariableForm
dynamically creates form fields based on the JSON attributes stored in thelabel
column of theVariableDatabase
model. However, when I visit the edit page in Flask-Admin, the edit form doesn't render any fields.I've verified that the form fields are being created correctly in the
VariableForm
class, but they are not appearing in the Flask-Admin interface.Could you please provide guidance on how to resolve this issue? I'd like to ensure that users can edit the variables directly in Flask-Admin without needing knowledge of JSON.