【发布时间】:2021-01-12 21:01:20
【问题描述】:
我正在尝试将 cmets 添加到我在 Flask 博客帖子网站上的帖子中,但我总是收到此错误 - sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column。
即使我创建了 db.Column 并且还使用了“db.create_all()”,它也会显示“没有这样的列”。
这是我的代码的简化版本:
routes.py 文件
@posts.route("/post/<int:post_id>", methods=["POST", "GET"])
@posts.route("/post/<int:post_id>/", methods=["POST", "GET"])
@login_required
def post(post_id): # every post has a unique ID
post = Post.query.get_or_404(post_id)
form = CommentForm()
comments = Comment.query.all()
if form.validate_on_submit():
comment = Comment(title=form.title.data, content=form.content.data)
db.session.add(comment)
db.session.commit()
return redirect(url_for("posts.post", post_id=post.id))
image_file = url_for("static", filename=f"profile_pictures/{current_user.image_file}")
return render_template("post.html", title=post.title, form=form, post=post, image_file=image_file)
models.py 文件
class Comment(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100))
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
content = db.Column(db.String(500), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False)
post_id = db.Column(db.Integer, db.ForeignKey("post.id"), nullable=False)
def __repr__(self):
return f"Comment('{self.title}', '{self.date_posted}')"
forms.py 文件
class CommentForm(FlaskForm):
title = StringField("Title (optional)", validators=[Length(max=100)])
content = TextAreaField("Content", validators=[DataRequired(), Length(max=500)])
submit = SubmitField("Reply")
HTML 代码
<form action="" method="POST">
{{ form.hidden_tag() }}
<fieldset class="form-group">
<div class="form-group">
{{ form.title.label(class="form-control-label") }}
{% if form.title.errors %}
{{ form.title(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.title.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.title(class="form-control form-control-lg") }}
{% endif %}
<ul class="ml-4">
<li><small class="text-muted">Must be less than 500 characters long.</small></li>
</ul>
</div>
<div class="form-group">
{{ form.content.label(class="form-control-label")}}
{% if form.content.errors %}
{{ form.content(class="form-control form-control-lg is-invalid", rows="7", cols="100") }}
{% for error in errors %}
<span>{{ error }}</span>
{% endfor %}
{% else %}
{{ form.content(class="form-control", rows="7", cols="100") }}
<ul class="ml-4">
<li><small class="text-muted">This field must not be empty.</small></li>
</ul>
{% endif %}
</div>
</fieldset>
<div class="form-group">
{{ form.submit(class="btn btn-info") }}
</div>
</form>
请有人帮助我 - 我被困了好几天不知道该怎么办。
【问题讨论】:
-
您能分享一下您的 sqlite 数据库的架构吗?您可以将其作为 UI 工具的屏幕截图附加到您的问题中,也可以通过 CLI 访问它并粘贴输出。