Forums

Why won't my script post the form data to the mysql database? (Python, Flask, and SQLAlchemy)

I'm very much a beginner at developing a flask app. I've been following the tutorial at http://blog.pythonanywhere.com/121/, as I am developing this app on PythonAnywhere. I don't get an error, but when I submit info on the add_lesson page, it redirects to my home page. When I check my mysql table, it's empty.

Here's the code:

from flask import Flask, redirect, render_template, request, url_for
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config["DEBUG"] = True

SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format(username="[MYUSERNAME]", password="[PASSWORD]", 
hostname="cobbmic.mysql.pythonanywhere-services.com", databasename="cobbmic$JimBSite",)

app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI

app.config["SQLALCHEMY_POOL_RECYCLE"] = 299


db = SQLAlchemy(app)


class Lessons(db.Model):


    __tablename__ = "lessons"

    id = db.Column(db.Integer, primary_key=True)
    url = db.Column(db.String(150))
    title = db.Column(db.String(80))
    series = db.Column(db.String(80))
    date = db.Column(db.Date())
    desc = db.Column(db.String(4096))

@app.route('/', methods=["GET","POST"])
def index():
    return render_template("index.html")

...

@app.route('/add_lesson', methods=["GET","POST"])
def add_lesson():
    if request.method == "GET":
        return render_template("add_lesson.html")

    lesson = Lessons(url=request.form["inputURL"], title=request.form["inputTitle"], series=request.form["inputSeries"], date=request.form["inputDate"], desc=request.form["inputDesc"])
    db.session.add(lesson)
    db.session.commit()
    return redirect(url_for('add_lesson'))

Anyone know what mistake I've made?

Does the form have the right action= attribute, is it definitely posting to the correct URL?

Thanks. I made a stupid mistake and didn't put action="/add_lesson". Sorry to bother you over such a trivial mistake.

No problem! Glad I could help :)