Forums

Database Connection Errors using SQLAlchemy to make a form

I am trying to create a form using Flask and SQLAlchemy, yet cannot seem to solve the error. After looking, I suppose it is something with the database connections. I do not really know what to do from here. I am trying to make a form where I can insert some data. For example, "Insert scholarship here", then after this the scholarships will be displayed on the home page, or wherever I choose the data to display.

Check out our Flask/MySQL tutorial -- it should explain everything you need to know.

I went through this tutorial, yet still had some errors in the database. I am not really sure where this was going on.

What error are you getting? What is the code?

There is an error that the database is not created, or something like that. Also, it doesn't let me do "from flask_app import db". The code is below:

flask_app.py --> main file

from datetime import datetime
from flask import Flask, redirect, render_template, request, url_for, flash
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import login_user, LoginManager, UserMixin, logout_user, login_required, current_user
from werkzeug.security import check_password_hash

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

SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format(
    username="gustavo123s",
    password="password123",
    hostname="gustavo123s.mysql.pythonanywhere-services.com",
    databasename="gustavo123s$scholarships",
)
app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
app.config["SQLALCHEMY_POOL_RECYCLE"] = 299
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
migrate = Migrate(app, db)

app.secret_key = "password123"
login_manager = LoginManager()
login_manager.init_app(app)

class User(UserMixin, db.Model):

    __tablename__ = "users"

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(128))
    password_hash = db.Column(db.String(128))

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)


    def get_id(self):
        return self.username

@login_manager.user_loader
def load_user(user_id):
    return User.query.filter_by(username=user_id).first()

class Scholarships(db.Model):

    __tablename__ = "scholarships"

    id = db.Column('scholarship_id', db.Integer, primary_key=True)
    scholarshipname = db.Column(db.String(100))
    deadline = db.Column(db.String(200))
    awardamount = db.Column(db.Float(50))
    eligibility = db.Column(db.String(100))
    requirements = db.Column(db.String(100))
    scholarshiptype = db.Column(db.String(200))
    applied = db.Column(db.String(100))
    awarded = db.Column(db.String(200))
    amountrecieved = db.Column(db.String(150))
    category = db.Column(db.String(50))

    def __init__(self, scholarshipname, deadline, awardamount, eligibility, requirements, scholarshiptype, applied, awarded, amountrecieved, category):
        self.scholarshipname = scholarshipname
        self.deadline = deadline
        self.awardamount = awardamount
        self.eligibility = eligibility
        self.requirements = requirements
        self.scholarshiptype = scholarshiptype
        self.applied = applied
        self.awarded = awarded
        self.amountrecieved = amountrecieved
        self.category = category

@app.route("/", methods=["GET", "POST"])
def list_scholarships():
    if request.method == "GET":
        return render_template("list_scholarships.html", Scholarships=Scholarships.query.all())

    if not current_user.is_authenticated:
        return redirect(url_for('index'))

@app.route('/add_scholarship', methods=['GET', 'POST'])
def addScholarship():
    if request.method == 'POST':
        if not request.form['scholarshipname'] or not request.form['deadline'] or not request.form['awardamount']:
            flash('Please enter all the fields', 'error')
        else:
            scholarship = Scholarships(request.form['scholarshipname'], request.form['deadline'], request.form['awardamount'],
            request.form['eligibility'], request.form['requirements'], request.form['scholarshiptype'], request.form['applied'], request.form['awarded'], request.form['amountrecieved'], request.form['category'])

            db.session.add(scholarship)
            db.session.commit()
            flash('record was successfully added')
            return redirect(url_for('list_scholarships'))
            #maybe--> insert above after list_scholarships, scholarshipname=scholarshipname, deadline=deadline...
    return render_template('add_scholarship.html', scholarships=Scholarships.query.all())
    #maybe enter the if __main__ here

#This is for the login feature, may not be relevant.
@app.route("/login/", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return render_template("login_page.html", error=False)

    user = load_user(request.form["username"])
    if user is None:
        return render_template("login_page.html", error=True)

    if not user.check_password(request.form["password"]):
        return render_template("login_page.html", error=True)

    login_user(user)
    return redirect(url_for('index'))

@app.route("/logout/")
@login_required
def logout():
    logout_user()
    return redirect(url_for('index'))

if __name__ == '__main__':
    db.create_all()
    app.run(debug=True)

list_scholarships.html --> templates folder

<!DOCTYPE html>
<html lang="en">
    <head><title>Home</title></head>
    <body>
        <h3>
            <a href="{{ url_for('list_scholarships')}}">Scholarship Management System</a>
        </h3>

        </hr>
        {%- for message in get_flashed_messages() %}
            {{ message }}
        {%- endfor %}

        <h3>Scholarships List</h3>
        <table border="2" padding="5">
            <thead>
                <tr>
                    <th>Scholarship Name</th>
                    <th>Deadline</th>
                    <th>Award Amount</th>
                    <th>Eligibility</th>
                    <th>Requirements</th>
                    <th>Scholarship Type</th>
                    <th>Applied?(Y/N)</th>
                    <th>Awarded?(Y/N)</th>
                    <th>Amount Recieved</th>
                    <th>Category</th>
                </tr>
            </thead>

            <tbody>
                {% for scholarship in Scholarships %}
                    <tr>
                        <td>{{ scholarship.scholarship name }}</td>
                        <td>{{ scholarship.deadline }}</td>
                        <td>{{ scholarship.award amount }}</td>
                        <td>{{ scholarship.eligibility }}</td>
                        <td>{{ scholarship.requirements }}</td>
                        <td>{{ scholarship.scholarship type }}</td>
                        <td>{{ scholarship.applied?(Y/N) }}</td>
                        <td>{{ scholarship.awarded?(Y/N) }}</td>
                        <td>{{ scholarship.amount recieved}}</td>
                        <td>{{ scholarship.category }}</td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
        <br><br>
        <a href="{{ url_for('addScholarship') }}">Add New Scholarship</a>
    </body>
</html>

add_scholarship.html --> templates folder

<!DOCTYPE html>
<html>
    <body>
        <h3>Add New Scholarship</h3>
        </hr>


        {%- for category, message in get_flashed_messages(with_categories = true) %}
            <div class="alert alert-danger">
                {{ message }}
            </div>
        {%- endfor %}

        <form action="{{ request.path }}" method="post">
            <label for="name">Scholarship Name</label><br>
            <input type="text" name="name" placeholder="Name" /><br>

            <label for="deadline">Deadline</label><br>
            <input type="text" name="deadline" placeholder="deadline" /><br>

            <label for="award amount">Award Amount</label><br>
            <input type="text" name="awdamount" placeholder="award amount" /><br>

            <label for="eligibility">Eligibility</label>
            <input type="text" name="eligibility" placeholder="eligibility" /><br>

            <label for="requirements">Requirements</label>
            <input type="text" name="requirements" placeholder="requirements" /><br>

            <label for="scholarship type">Scholarship Type</label>
            <input type="text" name="stype" placeholder="scholarship type" /><br>

            <label for="applied?(Y/N)">Applied?(Y/N)</label>
            <input type="text" name="applied" placeholder="applied?" /><br>

            <label for="awarded?(Y/N)">Awarded?(Y/N)</label>
            <input type="text" name="awarded" placeholder="awarded?" /><br>

            <label for="amount recieved">Amount Recieved</label>
            <input type="text" name="amt recieved" placeholder="amount recieved" /><br>

            <label for="category">Category</label>
            <input type="text" name="category" placeholder="category" /><br>

            <input type="submit" value="Submit" />
        </form>
    </body>
</html>

addition files for login system, may not be required. main_page.html --> templates folder

<html>
    <head>
        <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">
        <title>Scholarship Directory</title>
    </head>
    <body>
        <nav class="navbar navbar-inverse">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="#">My scratchpad</a>
                </div>
                <ul class="nav navbar-nav navbar-right">
                    {% if current_user.is_authenticated %}
                        <li><a href="{{ url_for('logout') }}">Log out</a></li>
                    {% else %}
                        <li><a href="{{ url_for('login') }}">Log in</a></li>
                    {% endif %}
                </ul>
            </div>
        </nav>

        <div class="container">

            {% for comment in comments %}
                <div class="row" style="margin-bottom: 1ex">
                    <div>
                        {{ comment.content }}
                    </div>
                    <div>
                        <small>
                            Posted
                            {% if comment.posted %}
                                {{ comment.posted.strftime("%A, %B %d %Y at %H:%M") }}
                            {% else %}
                                at an unknown time
                            {% endif %}
                            by
                            {% if comment.commenter %}
                                {{ comment.commenter.username }}
                            {% else %}
                                anonymous
                            {% endif %}
                        </small>
                    </div>
                </div>
            {% endfor %}

            {% if current_user.is_authenticated %}
            <div class="row">
                <form action="." method="POST">
                    <textarea name="contents" placeholder="Enter a comment"></textarea>
                    <input type="submit" class="btn btn-success" value="Post comment">
                </form>
            </div>
            {% endif %}
        </div>
    </body>
</html>

login_page.html --> templates folder

<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">

        <title>My scratchboard page: log in</title>
    </head>

    <body>
        <nav class="navbar navbar-inverse">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="#">My scratchpad: login page</a>
                </div>
            </div>
        </nav>

        <div class="container">

            <div class="row">
                {% if error %}
                    <div class="alert alert-warning" role="alert">
                        Incorrect username or password
                    </div>
                {% endif %}
                <form action="." method="POST">
                  <div class="form-group">
                    <label for="username">Username:</label>
                    <input class="form-control" id="username" name="username" placeholder="Enter your username">
                  </div>
                  <div class="form-group">
                    <label for="password">Password:</label>
                    <input type="password" class="form-control" id="password" name="password" placeholder="Enter your password">
                  </div>
                  <button type="submit" class="btn btn-success">Log in</button>
                </form>
            </div>

        </div>

    </body>
</html>

--end of code--

I just want to get the database to work or connect and know how to do this correctly, since the page shows nothing.

[formatted by admin]

Did you check the error logs? It looks like you're trying to look up the table that doesn't exist (i.e. scholarships).