'Error occurs when I try to create a new column with passwords in database [duplicate]

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


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///passwords.db'

db = SQLAlchemy(app)


class Passwords(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(200), nullable=False)
    key = db.Column(db.String(200), nullable=False)
    date_created = db.Column(db.DateTime, default=datetime.utcnow)

    def __repr__(self):
    return '<Name %r>' % self.id


@app.route("/passwords")
def passwords():
return render_template("passwords.html")


@app.route("/")
def home():
    return render_template("index.html")


@app.route("/signup", methods=["POST", "GET"])
def new_user():
    if request.method == "POST":
        a = str(uuid.uuid4())
        print(a)
        key = Passwords(key=a)
        username = request.form["nm"]
        newuser = Passwords(name=username)
        try:
            db.session.add(newuser)
            db.session.commit()
            db.session.add(key)
            db.session.commit()
            return redirect(url_for("new_user"))
        except:
            return "There was an error with your registration"
    else:
        passcodes = Passwords.query.order_by(Passwords.date_created)
        return render_template("signup.html", passcodes=passcodes)


@app.route("/login", methods=["POST", "GET"])
def login():
    a = str(uuid.uuid4())
    print(a)
    if request.method == "POST":
        user = request.form["pw"]
        if user == a:
            return redirect(url_for("user", usr='Η Ακύρωση κράτησης ολοκληρώθηκε'))
        else:
            return render_template("login.html")
    else:

        return render_template("login.html")


@ app.route("/<usr>")
def user(usr):
    return "<h1>{}</h1>".format(usr)


if __name__ == "__main__":
    app.run(debug=True)

I get my website up and running but when I go to /signup, an error occurs:

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: passwords.key
[SQL: SELECT passwords.id AS passwords_id, passwords.name AS passwords_name, passwords."key" AS passwords_key, passwords.date_created AS passwords_date_created FROM passwords ORDER BY passwords.date_created]
(Background on this error at: https://sqlalche.me/e/14/e3q8)

Any help is much appreciated



Solution 1:[1]

SQLAlchemy only handles creating and dropping tables; it has no support for adding, removing or amending columns, other than executing raw SQL ALTER TABLE statements. If you need to perform such an action your options are, in ascending order of difficulty*:

  • Drop the entire database (or delete the SQLite file) and run db.create_all() to recreate it
    • all data will be lost unless you back up the database
  • Drop the affected table and run db.create_all() to recreate it
    • Use your database's console or some other database management application to drop the table
    • If the table is related to other tables via foreign keys then the related tables may need to be deleted too
    • All data in the table will be lost unless it's backed up
  • Manually execute the necessary ALTER TABLE statement(s) in your database's console or some other database management application
    • You will need to ensure that the results match what SQLAlchemy would have created
  • Use a migration utility to apply model changes to the database

* All options assume you have updated the model class

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 snakecharmerb