Home > Software design >  Flask: How to access current user when creating forms?
Flask: How to access current user when creating forms?

Time:01-03

I have found this question asked in various ways slightly different but the answers seemed old or not quite what I was looking for. I have a functioning Flask application with Flask-Security and some WTF Forms. Users can login, fill up forms and all, everything is fine.

Now, I have the need to access a user setting (shirt size) while creating a form so it is displayed to the user as they fill the form (so this is not a validation problem). I added to the form file: from flask_security import current_user to access the setting current_user.ts_size but I am faced with the AttributeError: 'NoneType' object has no attribute 'ts_size'

I understand that this means that current_user is of NoneType, the question is why? I am using the same import line in the file that defines the views without any problem. The views are decorated with auth_required so by the time a form needs to be created and displayed to the user, it is already check that the user is authenticated. What am I missing?

from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired
from flask_security import current_user

class JacketForm(FlaskForm):
  material = StringField(validators=[DataRequired()],)
  size = StringField(validators=[DataRequired()], cur_size=current_user.ts_size) 

CodePudding user response:

you have to import current_user from flask_login, not from flask_security

CodePudding user response:

There are a few things going on on your code. First - remember that the field definitions are class variables - so those don't change when a form is instantiated. Second - StringField doesn't have a keyword argument 'cur_size' - it does have a keyword argument 'default' - which can be a callable!

So try something like:

size = StringField(validators=[DataRequired()], default=lambda: current_user.ts_size)
  • Related