Adding comments to a flask blog webapp

I am trying to add comments to my posts. I am on step 1, where I manually go to url/post/post_id/comment (based on route).

This will show me a form, and that form once validated, will update the db.

Here is the code for the models:

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}')" 

Form:

class AddCommentForm(FlaskForm): body = StringField("Body", validators=[DataRequired()]) submit = SubmitField("Post") 

This is my view function:

@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) 

And this is the template:

{% extends "layout.html"%} {% block content %} <div> <form method="POST" action=""> {{ form.hidden_tag() }} <fieldset> <legend>Comment</legend> <div> {{ form.body.label(class="form-control-label") }} {% if form.body.errors %} {{ form.body(class="form-control form-control-lg is-invalid") }} <div> {% for error in form.body.errors %} <span>{{ error }}</span> {% endfor %} </div> {% else %} {{ form.body(class="form-control form-control-lg") }} {% endif %} </div> </fieldset> <div> {{ form.submit(class="btn btn-outline-info") }} </div> </form> </div> {% endblock content %} 

The issue I am runnign into, is that the form doesn't seem to validate, i.e in the route I can get a flash message if I post it right above the "form.validate_on_submit".

But, it seems like even when i "Submit" the form in html, it doesnt go into the "if" loop.

What am I missing here?

0

1 Answer

The first thing I see that is wrong is that your action attribute is empty and that means when you submit the form, it goes nowhere.

Fix it by adding in your html an action attribute that points to the route that handles the form.

{% extends "layout.html"%} {% block content %} <div> <form method="POST" action="{{url_for('comment_post', post_id=str(post_id))}}"> {{ form.hidden_tag() }} <fieldset> <legend>Comment</legend> <div> {{ form.body.label(class="form-control-label") }} {% if form.body.errors %} {{ form.body(class="form-control form-control-lg is-invalid") }} <div> {% for error in form.body.errors %} <span>{{ error }}</span> {% endfor %} </div> {% else %} {{ form.body(class="form-control form-control-lg") }} {% endif %} </div> </fieldset> <div> {{ form.submit(class="btn btn-outline-info") }} </div> </form> </div> {% endblock content %} 

in your route code you should do the following:

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) 

Lastly, Try and use InputRequired() validator instead.

from wtforms.validators import InputRequired class AddCommentForm(FlaskForm): body = StringField("Body", validators=[InputRequired()]) submit = SubmitField("Post") 
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like