sqlite Sqlalchemy.exc.NoReferencedTableError

j0pj023g  于 2022-12-19  发布在  SQLite
关注(0)|答案(1)|浏览(137)

我在 flask 中创建一个简单的博客。我已经创建了用户和帖子2个模型。下面给出了www.example.com文件的代码main.py。

from flask import Flask
from flask import render_template
from flask import url_for
from forms import RegistrationForm, LoginForm
from flask import flash
from flask import redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)
app.config['SECRET_KEY'] = 'b91bfa7c7111f5ced35cb6431ae5d341'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    image_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.image_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"Post('{self.title}','{self.date_posted}')"

@app.route('/')
def home_page():
    return render_template('home_page.html', posts=posts, title='Home-Page')

@app.route('/about')
def about_page():
    return render_template('about_page.html', title='About-Page')

@app.route('/register', methods=['POST', 'GET'])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        flash(f'Account Created for {form.username.data} !', 'success')
        return redirect(url_for('home_page'))
    return render_template('register.html', form=form, title='Register')

@app.route('/login', methods=['POST', 'GET'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        if form.email.data == 'admin@blog.com' and form.password.data =='admin':
            flash('Login Successful', 'success')
            return redirect(url_for('home_page'))
        else:
            flash('Login unsuccessful, Please check credentials', 'danger')
    return render_template('login.html', form=form, title='Login')

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

然后我使用了以下命令

from main import db
db.create_all()

这一直显示以下错误
sqlalchemy.exc.NoReferencedTableError:与列'post.user_id'关联的外键找不到表'user_id',无法使用该表生成指向目标列'None'的外键

gj3fmq9x

gj3fmq9x1#

您需要引用ForeignKey中的目标表名和列名,因此,行:

user_id = db.Column(db.Integer, db.ForeignKey('user_id'), nullable=False)

应为:

user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

相关问题