我想在帖子中添加评论。我在第1步,我手动转到url / post / post_id / comment(基于路由)。
这将向我显示一个表单,该表单一旦验证,将更新数据库。
以下是模型的代码:
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='article', 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)
body = db.Column(db.String(100), nullable=False)
timestamp = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)
def __repr__(self):
return f"Comment('{self.body}', '{self.timestamp}')"
形成:
class AddCommentForm(FlaskForm):
body = StringField("Body", validators=[DataRequired()])
submit = SubmitField("Post")
这是我的视图功能:
@app.route("/post/<int:post_id>/comment", methods=["GET", "POST"])
@login_required
def comment_post(post_id):
post = Post.query.get_or_404(post_id)
form = AddCommentForm()
if form.validate_on_submit():
comment = Comment(body=form.body.data, article=post.id)
db.session.add(comment)
db.session.commit()
flash("Your comment has been added to the post", "success")
return redirect(url_for("post", post_id=post.id))
return render_template("comment_post.html", title="Comment Post", form=form)
这是模板:
{% extends "layout.html"%}
{% block content %}
<div class="content-section">
<form method="POST" action="">
{{ form.hidden_tag() }}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Comment</legend>
<div class="form-group">
{{ form.body.label(class="form-control-label") }}
{% if form.body.errors %}
{{ form.body(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.body.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.body(class="form-control form-control-lg") }}
{% endif %}
</div>
</fieldset>
<div class="form-group">
{{ form.submit(class="btn btn-outline-info") }}
</div>
</form>
</div>
{% endblock content %}
我遇到的问题是,表单似乎没有验证,即如果我在“form.validate_on_submit”上面发布它,我可以获得一条flash消息。
但是,即使我在html中“提交”表单,它似乎也没有进入“if”循环。
我在这里错过了什么?
我看到的第一件事是错误的是你的action
属性是空的,这意味着当你提交表单时,它无处可去。
通过在html中添加指向处理表单的路由的action
属性来修复它。
{% extends "layout.html"%}
{% block content %}
<div class="content-section">
<form method="POST" action="{{url_for('comment_post', post_id=str(post_id))}}">
{{ form.hidden_tag() }}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Comment</legend>
<div class="form-group">
{{ form.body.label(class="form-control-label") }}
{% if form.body.errors %}
{{ form.body(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.body.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.body(class="form-control form-control-lg") }}
{% endif %}
</div>
</fieldset>
<div class="form-group">
{{ form.submit(class="btn btn-outline-info") }}
</div>
</form>
</div>
{% endblock content %}
在您的路线代码中,您应该执行以下操作:
from flask import request
@app.route("/post/<int:post_id>/comment", methods=["GET", "POST"])
@login_required
def comment_post(post_id):
post = Post.query.get_or_404(post_id)
form = AddCommentForm()
if request.method == 'POST': # this only gets executed when the form is submitted and not when the page loads
if form.validate_on_submit():
comment = Comment(body=form.body.data, article=post.id)
db.session.add(comment)
db.session.commit()
flash("Your comment has been added to the post", "success")
return redirect(url_for("post", post_id=post.id))
return render_template("comment_post.html", title="Comment Post",
form=form, post_id=post_id)
最后,尝试并使用InputRequired()
验证器。
from wtforms.validators import InputRequired
class AddCommentForm(FlaskForm):
body = StringField("Body", validators=[InputRequired()])
submit = SubmitField("Post")