import os
from flask import Flask, render_template, redirect, url_for, request
from flask_login import LoginManager, UserMixin, login_user, current_user, logout_user
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///db.sqlite"
db = SQLAlchemy()
login_manager = LoginManager(app)
class Users(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(250), unique=True,
nullable=False)
password = db.Column(db.String(250),
nullable=False)
location = db.Column(db.String(250),
nullable=False)
db.init_app(app)
app.app_context().push()
with app.app_context():
db.create_all()
@login_manager.user_loader
def loader_user(user_id):
return Users.query.get(user_id)
@app.route('/register', methods=["GET", "POST"])
def register():
if request.method == "POST":
if not db.session.query(Users).filter_by(username=request.form.get("uname")).count() < 1:
return render_template("sign_up.html", value = "USER ALREADY EXISTS")
if request.form.get("uname") == "":
return render_template("sign_up.html", value = "USERNAME IS BLANK")
if request.form.get("psw") == "":
return render_template("sign_up.html", value = "PASSWORD IS BLANK")
if request.form.get("loc") == "":
return render_template("sign_up.html", value = "LOCATION IS BLANK")
user = Users(username=request.form.get("uname"),
password=request.form.get("psw"),
location=request.form.get("loc"))
db.session.add(user)
db.session.commit()
return redirect(url_for("login"))
return render_template("sign_up.html", value ="")
@app.route("/login", methods=["GET", "POST"])
def login():
if current_user.is_authenticated:
return redirect(url_for("index", logged_in = True, username = current_user.username))
if request.method == "POST":
user = Users.query.filter_by(
username=request.form.get("uname")).first()
if not user:
return render_template("login.html", value = request.form.get("uname"))
if user.password == request.form.get("psw"):
login_user(user)
return redirect(url_for("index", logged_in = True, username = user.username))
return render_template("login.html")
if __name__ == "__main__":
app.secret_key = 'kevin2000'
app.config['SESSION_TYPE'] = 'filesystem'
app.run(host ="0.0.0.0", port = 10000, debug=False)
This is my code and here i am getting this error
Traceback (most recent call last):
File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\base.py", line 1964, in _exec_single_context
self.dialect.do_execute(
File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\default.py", line 945, in do_execute
cursor.execute(statement, parameters)
sqlite3.OperationalError: no such table: users
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\flask\app.py", line 1511, in wsgi_app
response = self.full_dispatch_request()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\flask\app.py", line 919, in full_dispatch_request
rv = self.handle_user_exception(e)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\flask\app.py", line 917, in full_dispatch_request
rv = self.dispatch_request()
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\flask\app.py", line 902, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) # type: ignore[no-any-return]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\theco\OneDrive\Documents\veil\app.py", line 41, in register
if not db.session.query(Users).filter_by(username=request.form.get("uname")).count() < 1:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\orm\query.py", line 3147, in count
self._legacy_from_self(col).enable_eagerloads(False).scalar()
File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\orm\query.py", line 2836, in scalar
ret = self.one()
^^^^^^^^^^
File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\orm\query.py", line 2809, in one
return self._iter().one() # type: ignore
^^^^^^^^^^^^
File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\orm\query.py", line 2858, in _iter
result: Union[ScalarResult[_T], Result[_T]] = self.session.execute(
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\orm\session.py", line 2365, in execute
return self._execute_internal(
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\orm\session.py", line 2251, in _execute_internal
result: Result[Any] = compile_state_cls.orm_execute_statement(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\orm\context.py", line 306, in orm_execute_statement
result = conn.execute(
^^^^^^^^^^^^^
File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\base.py", line 1416, in execute
return meth(
^^^^^
File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\sql\elements.py", line 523, in _execute_on_connection
return connection._execute_clauseelement(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\base.py", line 1638, in _execute_clauseelement
ret = self._execute_context(
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\base.py", line 1843, in _execute_context
return self._exec_single_context(
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\base.py", line 1983, in _exec_single_context
self._handle_dbapi_exception(
File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\base.py", line 2352, in _handle_dbapi_exception
raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\base.py", line 1964, in _exec_single_context
self.dialect.do_execute(
File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\default.py", line 945, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: users
[SQL: SELECT count(*) AS count_1
FROM (SELECT users.id AS users_id, users.username AS users_username, users.password AS users_password, users.location AS users_location
FROM users
WHERE users.username = ?) AS anon_1]
[parameters: ('xdgsdg',)]
(Background on this error at: https://sqlalche.me/e/20/e3q8)
I've searched in other places but it's just said about the db.create_all() not being there im pretty new to flask as well so someone help please
i also tried db.drop_all() then db.create_all()
that also didn't seem to work
if it helps i can also provide the sign_up.html from which the error is occuring when i submit the form
The error about no such column: location
mentioned in your question is different from the actual traceback, which is showing a no such table: users
error. However I see the issue. You're initializing Flask-SQLAlchemy after defining routes, but before initializing app context. You need to move your configuration settings to the top, right after creating the Flask app, then initialize db with app immediately.
Your code will then look like this -
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///db.sqlite"
app.secret_key = 'kevin2000'
app.config['SESSION_TYPE'] = 'filesystem'
db = SQLAlchemy(app)
class Users(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(250), unique=True, nullable=False)
password = db.Column(db.String(250), nullable=False)
location = db.Column(db.String(250), nullable=False)
login_manager = LoginManager(app)
with app.app_context():
db.create_all()
@app.route('/')
def index():
return render_template('index.html')
*/ add the remaining routes here