Reputation: 41
run.py file:
from flaskblog import app, db
if __name__ == '__main__':
db.create_all()
app.run(debug=True)
models.py file:
from flaskblog import db
from datetime import datetime
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
img_file = db.Column(db.String(20), nullable=False, default='default.jpeg')
password = db.Column(db.String(60), nullable=False)
posts = db.relationship('Post', backref='author', lazy=True)
def __repr__(self):
return f"User('{ self.username }', '{ self.email }', '{ self.img_file }')"
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
content = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
def __repr__(self):
return f"User { self.title }, { self.date_posted })"
init.py file:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
from flaskblog import routes
I have tried creating the table using the terminal before running the app using db.create_all()
but it still didn't work.
The following error is thrown:
SQLAlchemy.exc.OperationalError : (sqlite3.OperationalError) no such table: user
If anyone could solve this problem, I would really appreciate it. Thanks.
Upvotes: 3
Views: 4663
Reputation: 682
#from flaskblog import db <- this import is wrong!
from my_project_name import db # the instancfe of SQLAlchemy that you use in your app
from datetime import datetime
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
img_file = db.Column(db.String(20), nullable=False, default='default.jpeg')
password = db.Column(db.String(60), nullable=False)
posts = db.relationship('Post', backref='author', lazy=True)
def __repr__(self):
return f"User('{ self.username }', '{ self.email }', '{ self.img_file }')"
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
content = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
def __repr__(self):
return f"User { self.title }, { self.date_posted })"
Upvotes: 2