Cannot add comment to SQL db in python Flask app
Question: I am new to programming and have setup a small website with a comments section
on pythonanywhere.com, relaying heavily on their tutorial. But when I post a
comment in the form, the comment is not added to the database and for some
reason the program redirects me to the index page (the intention is to
redirect to stay on the same page)

Any suggestions as to what I might be doing wrong would be greatly
appreciated!

The pyhthon code:

    
    
    import random
    from flask import Flask, request, session, redirect, url_for, render_template, flash
    from flask.ext.sqlalchemy import SQLAlchemy
    from werkzeug.routing import RequestRedirect
    
    app = Flask(__name__)
    app.config["DEBUG"] = True
    
    SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format(
        username="username",
        password="password",
        hostname="hostname",
        databasename="majaokholm$majaokholm",
    )
    app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
    app.config["SQLALCHEMY_POOL_RECYCLE"] = 299
    
    db = SQLAlchemy(app)
    
    class Comment(db.Model):
    
        __tablename__ = "comments"
    
        id = db.Column(db.Integer, primary_key=True)
        content = db.Column(db.String(4096))
    
    @app.route("/")
    def index():
        return render_template("index_page.html")
    
    @app.route('/post', methods=["GET", "POST"])
    def post():
        if request.method == "GET":
            return render_template("post_page.html", comments=Comment.query.all())
        comment = Comment(content=request.form["contents"])
        db.session.add(comment)
        db.session.commit()
        return redirect(url_for('post'))
    

and the form from the HTML template:

    
    
    <form action="." method="POST">
    <textarea class="form-control" name="contents" placeholder="Enter a 
    comment"></textarea>
    <input type="submit" value="Post comment">
                    </form>
    

Thanks a lot in advance!


Answer: Currently, the `action="."` in the form actually points to the root of the
current directory, which for `/post` happens to be just `/` and thus points to
the `index`.

It's always better to use `action="{{ url_for('your_target_view') }}"`
instead.

