How to use current_user in model_form

379 Views Asked by At

I need to filter a select menu showing only groups in a user's company. With sqlalchemy there was the QuerySelectField, however, this does not seem to be available in flask-mongoengine. Ideally, I would like to pass flask_login current_user to model_form as follows:

wtfUser = model_form(User, wtf.Form, exclude=[ 'password'], field_args = {
    'group' : { 'queryset': Group.objects(company = current_user.group.company) },
    'roles' : { 'queryset': Role.objects(name__ne = 'admin').order_by('name') }
})

However, since this places current_user outside the request context, this results in errors. Does anyone have a clever idea on how to do this?

1

There are 1 best solutions below

0
On

Not the most elegant approach, however, it works. In views.py I do the following. If you have a better approach please post.

def user(id):
    user = User.objects.get_or_404(id = id)
    wtf_user = wtfUser(obj = user)
    wtf_user.group.queryset = Group.objects(id = current_user.group.id)
    return render_template('user.html', wtf_user = wtf_user)