Flask-AppBuilder icon indicating copy to clipboard operation
Flask-AppBuilder copied to clipboard

About dynamic change column label for a modelview

Open QKJIN opened this issue 2 years ago • 3 comments

I want to change a modelview column labels dynamic. I use a table to save the column labels. And in mymodelview class, I use a method to get them like below.

def get_label_column(modelname):
    items = db.session.query(Label).filter(Label.model_name==modelname)
    label_column = dict()
    for item in items:
        label_column[item.column_name]=item.column_label
    return label_column


class MyModelView(ModelView):
...
    label_columns = get_label_column(modelname)
...

When I change the column label, I don't know how to reload MyModelView. The column labels are still not changed except I rerun this app. So how to reload one modelview if its properties are changed dynamiclly without rerunning app.

QKJIN avatar Jul 21 '22 10:07 QKJIN

You have to do that on instance level. Overriding render_template method should do the trick.

from flask import render_template

class MyModelView(ModelView):

  def render_template(self, template, **kwargs):
          """
              Use this method on your own endpoints, will pass the extra_args
              to the templates.
  
              :param template: The template relative path
              :param kwargs: arguments to be passed to the template
          """
          kwargs["base_template"] = self.appbuilder.base_template
          kwargs["appbuilder"] = self.appbuilder
          self.label_columns = get_label_column(modelname)
          return render_template(
              template, **dict(list(kwargs.items()) + list(self.extra_args.items()))
          )

ThomasP0815 avatar Jul 21 '22 21:07 ThomasP0815

@ThomasP0815 Thank you very much. It works when I override this method. I changed the labels in db table, then refresh the modelview list page, those columns lables are changed.

But there is still a little problem. After I changed the labels and save, I visit the modelview list link. The column labels on the web page are still original. I must refresh the page or reclick this page link, then the changed column lables can display. I am wonder why the overrided render_tempate can not update the label_columns at the first time to visit the modelview list page after the labels have been changed. It's very strange.

QKJIN avatar Jul 22 '22 03:07 QKJIN

Probably there is some caching in between (Browser, ORM)

ThomasP0815 avatar Jul 22 '22 13:07 ThomasP0815