2

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!

dirn
21.1k7 gold badges75 silver badges76 bronze badges
asked Apr 8, 2016 at 6:53
2
  • PS. Be careful with credentials... Commented Apr 8, 2016 at 7:07
  • Hey!!! You're revealing your database credentials. I can see your username & password. Commented Apr 8, 2016 at 9:01

2 Answers 2

2

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.

answered Apr 8, 2016 at 7:06
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explanation!
0

get rid of action=".", you can use action=""

answered Apr 8, 2016 at 7:21

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.