I've been beating my head again this one all day. So I am trying to build a simple Flask application with Flask-SQLAlchemy and Flask-Login. My user class for Flask-Login looks like this:
class SiteUser(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String, nullable=False, unique=True)
password = db.Column(db.String, nullable=False)
I also have a class to store content for a user that looks something like this and establishes a one to many relationship from the user to the content:
class UserContent(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.Text, nullable=False)
author_id = db.Column(db.Integer, db.ForeignKey('site_user.id'))
author = db.relationship(SiteUser, backref=db.backref('contents', lazy='dynamic'))
When I create the content in the data I am using this logic:
new_content = UserContent(content=form_content, author=current_user)
db.session.add(new_content)
db.session.commit()
I am getting a frustrating InvalidRequestError at the line where I add the model instance to the session. SQLAlchemy tells me that the UserContent object is already attached to a different session. But I thought that Flask-SQLAlchemy was supposed to remove sessions automatically at the end of every request. The current_user is of course the Flask-Login variable that has the user who is logged in at the moment. If I omit the author when creating new UserContent, it works so the problem must be with how I am loading the current user in the Flask-Login user loader function which I have here:
@login_manager.user_loader
def user_loader(id):
user = SiteUser.query.get(id)
if user is not None:
return user
return
The only other place in the app so far that I am touching the database is when authenticating the user but that code is not throwing an error. I've tried this with both SQLite and PostgreSQL but still get the same error. Does anyone see something that I am missing?
Thanks! :)