AttributeError:“函数”对象没有属性“ _sa_instance_state”

时间:2020-03-21 03:20:32

标签: python database flask model relationship

我正在为社交媒体网站创建博客帖子功能。但是,当我单击发布按钮以发布博客时,该网站不会将我重定向到我在终端中显示错误时插入的模板:'AttributeError:'function'对象没有属性'_sa_instance_state'。

看着回溯,我发现与用户模型和BlogPost模型之间的关系有关。

以下是我的模型(或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}" ```

以下是我对发布博客的观点(或views.py)的代码:

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)

这是模板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 %}

以下是我的完整追溯: enter image description here Traceback.imagem.no1

1: P /秒使用用户模型,所有视图,模板和代码都可以正常工作。 我是学生,正在创建一个项目。我的计算机科学老师无法帮助我,所以我真的很困。请,请帮助。谢谢!

2 个答案:

答案 0 :(得分:1)

在user_post的第93行,您需要在定义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)

答案 1 :(得分:-1)

编辑:这是一个错误的答案,但我很好奇是否可行

O

在user_post的第94行,您需要呼叫homeuser ... filter_by(creator=homeuser()),而不是filter_by(creator=homeuser)