1

If the current user role = admin then show all the records in the table. If not, then limit the rows by created user.

I can get the user name if I define a function in the View Class, but need it before the list is constructed. See source code below.

from flask_appbuilder.models.sqla.filters import FilterEqualFunction
from app import appbuilder, db
from app.models import Language
from wtforms import validators, TextField
from flask import g
from flask_appbuilder.security.sqla.models import User

def get_user():
    return g.user

class LanguageView(ModelView):
    datamodel = SQLAInterface(Language)
    list_columns = ["id", "name"]
    base_order = ("name", "asc")
    page_size = 50

    #This is the part that does not work - unable to import app Error: Working outside of application context
    #If the user role is admin show all, if not filter only to the specific user
    if g.user.roles != "admin":
        base_filters = [['created_by', FilterEqualFunction, get_user]]    

This is the error I'm getting:

Was unable to import app Error: Working outside of application context.

This typically means that you attempted to use functionality that needed to interface with the current application object in some way. To solve this, set up an application context with app.app_context(). See the documentation for more information.

Sam Carlson
  • 1,891
  • 1
  • 17
  • 44
mowensa
  • 11
  • 5

2 Answers2

0

In this case it is better to create two different ModelViews, one for users with base_filters = [['created_by', FilterEqualFunction, get_user]] and the second for admins only without any filtering.

And do not forget to specify correct permissions for both.

Ramil Gataullin
  • 131
  • 2
  • 5
0

In my case, I created new filter FilterStartsWithFunction by coping FilterStartsWith(You can find the source code in Flask-Appbuilder pack easily. ). see the codes

from flask_appbuilder.models.sqla.filters import get_field_setup_query

class FilterStartsWithFunction(BaseFilter):
    name = "Filter view with a function"
    arg_name = "eqf"

    def apply(self, query, func):
        query, field = get_field_setup_query(query, self.model, self.column_name)
        return query.filter(field.ilike(func() + "%"))

def get_user():
    if 'Admin' in [r.name for r in g.user.roles]:
        return ''
    else:
        return g.user.username

...
...

    base_filters = [['created_by',FilterStartsWithFunction,get_user]]