因此,我正在尝试创建一个博客,该博客具有可以创建帖子的用户,在任何帖子中都应该有用户撰写的评论。
那是我的代码:
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), nullable=False, unique=True)
email = db.Column(db.String(120), nullable=False, unique=True)
password = db.Column(db.String(60), nullable=False)
image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
posts = db.relationship('Post', backref='author', lazy=True)
comments = db.relationship('Comment', backref='commentauthor', lazy=True)
def __repr__(self):
return f"User('{self.username}','{self.email}','{self.image_file}')"
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
content = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
comments = db.relationship('Comment', backref='postcontainer', lazy=True)
def __repr__(self):
return f"Post('{self.title}', '{self.date_posted}')"
class Comment(db.Model):
id = db.Column(db.Integer, primary_key=True)
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
content = db.Column(db.Text, nullable=False)
post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
def __repr__(self):
return f"Comment('{self.content}', '{self.date_posted}')"
也是我路线上的代码:
@app.route("/", methods=['POST', 'GET'])
def home():
page = request.args.get('page', 1, type=int)
posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page, per_page=5)
cpost = CreatePost()
if cpost.validate_on_submit():
post = Post(title=cpost.title.data, content=cpost.content.data, author=current_user)
db.session.add(post)
db.session.commit()
return redirect(url_for('home'))
ccomment = CreateComment()
comments = Comment.query.all()
if ccomment.validate_on_submit():
comment = Comment(content=ccomment.content.data)
db.session.add(comment)
db.session.commit()
return redirect(url_for('home'))
return render_template('home.html', posts=posts, cpost=cpost, ccomment=ccomment, comments=comments)
我最终收到此错误:
sqlalchemy.exc.OperationalError:(sqlite3.OperationalError)否这样 表格:comment [SQL:SELECT comment.id AS comment_id, comment.date_posted AS comment_date_posted,comment.content AS comment_content,comment.post_id AS comment_post_id,comment.user_id AS comment_user_id FROM comment](此错误的背景位于: http://sqlalche.me/e/e3q8)
回溯(最近通话最近一次)
我该如何解决?
答案 0 :(得分:0)
您需要在数据库中创建注释表,如果您使用flask-sqlalchemy扩展名,则只需调用此函数https://flask-sqlalchemy.palletsprojects.com/en/2.x/api/#flask_sqlalchemy.SQLAlchemy.create_all
https://flask-sqlalchemy.palletsprojects.com/en/2.x/quickstart/
答案 1 :(得分:0)
转到您的python shell窗口并输入:
from name import db
db.create_all()
name
是您的项目的名称。