向Flask博客Web应用添加评论

时间:2018-08-30 21:13:02

标签: flask flask-sqlalchemy

我正在尝试在我的帖子中添加评论。我在第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”上方,则可以得到即显消息。

但是,即使我以html形式提交表单,它也不会进入“ if”循环。

我在这里想念什么?

1 个答案:

答案 0 :(得分:0)

我发现第一件事是错误的,那就是您的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")