AttributeError: 'function' object has no attribute '_sa_instance_state'
Answer a question
I'm creating a blog post function for a social media website. However, when I clicked the post button to post a blog, the website doesn't redirect me to the template I put in while showing an error in my terminal: 'AttributeError: 'function' object has no attribute '_sa_instance_state'.
Looking at the traceback, I saw that there are something to do with the relationship I did between the User and the BlogPost models.
Here is the code for my models(or models.py):
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from datetime import datetime
@login_manager.user_loader
def load_user(user_id):
return User.query.get(user_id)
class User(db.Model, UserMixin):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
profile_image = db.Column(db.String(64), nullable=False, default='default_profile.jpg' )
email = db.Column(db.String(64), unique=True, index=True)
first_name = db.Column(db.String(20))
last_name = db.Column(db.String(20))
username = first_name + last_name
password_hash = db.Column(db.String(128))
posts = db.relationship('BlogPost', backref='creator', lazy=True)
def __init__(self,email,first_name,last_name, password):
self.email = email
self.first_name = first_name
self.last_name = last_name
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
def __repr__(self):
return f"Username: {self.username}"
class BlogPost(db.Model):
users = db.relationship(User)
blog_id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer,db.ForeignKey('users.id'), nullable=False) #users.id is taken from the tablename(users) and id in its table
date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
problem_name = db.Column(db.String(140), nullable=False)
text = db.Column(db.Text, nullable=False)
def __init__(self, text, problem_name, user_id):
self.text = text
self.problem_name = problem_name
self.user_id = user_id
def __repr__(self):
return f"Post ID: {self.post_id} -- Date:{self.date}---{self.problem_name}" ```
Here is the code for my views(or views.py) of the posting blog:
blog_posts = Blueprint('blog_posts',__name__)
@blog_posts.route('/create', methods=['GET', 'POST'])
@login_required
def create_post():
form = BlogPostForm()
if form.validate_on_submit():
blog_validated = BlogPost(problem_name=form.problem_name.data,
text=form.text.data,
user_id=current_user.id
)
db.session.add(blog_validated)
db.session.commit()
flash('Blog Post Created')
return redirect(url_for('core.index'))
return render_template('create_post.html', form=form)
And here is the code for the template create_post.html:
{% extends "base.html" %}
{% block content %}
<div class="container">
<form method="POST" >
{{ form.hidden_tag() }}
{{ form.problem_name.label(class="form-control-label") }} {{ form.problem_name(class="form-group form-control") }}<br>
{{ form.text.label }} {{ form.text(class="form-group form-control") }}<br>
{{ form.problem_submit.label(class="btn btn-secondary")}}
</form>
</div>
{% endblock %}
Below is my full traceback:
1: P/s. All the views and templates and codes work well using the User model. I'm a student and I'm creating a project. My computer science teacher can't help me so I'm really stuck. Please, please help. Thank you!
Answers
On line 93 in user_post you need to put parentheses on the end of the line that defines home_user
.
@users.route('/<username>')
def user_posts(username):
page = request.args.get('page',1,type=int)
home_user = User.query.filter_by(username=username).first_or_404() # <= You're missing the ()
blog_posts = BlogPost.query.filter_by(creator=home_user).order_by(BlogPost.date.desc()).paginate(page=page, per_page=5) return render_template('user_blog_posts.html', blog_posts=blog_posts, home_user=home_user)
更多推荐
所有评论(0)