python - 获取 sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL 约束失败:user.image_file

我是学习 Flask 的新手。在 youtube 教程之后,我做了和培训师一样的事情。但是我收到了完整性错误。

Flask_Blog.Py:

from datetime import datetime
from flask import Flask, render_template, url_for, flash, redirect
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.com import dynamic

from forms import RegistrationForm, LoginForm

app = Flask(__name__)
app.config['SECRET_KEY'] = '5791628bb0b13ce0c676dfde280ba245'
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)
    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}')"


posts = [
    {
        'author': 'Corey Schafer',
        'title': 'Blog Post 1',
        'content': 'First post content',
        'date_posted': 'April 20, 2018'
    },
    {
        'author': 'Jane Doe',
        'title': 'Blog Post 2',
        'content': 'Second post content',
        'date_posted': 'April 21, 2018'
    }
]


@app.route("/")
@app.route("/home")
def home():
    return render_template('home.html', posts=posts)


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


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


@app.route("/login", methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        if form.email.data == 'admin@blog.com' and form.password.data == 'password':
            flash('You have been logged in!', 'success')
            return redirect(url_for('home'))
        else:
            flash('Login Unsuccessful. Please check username and password', 'danger')
    return render_template('login.html', title='Login', form=form)

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

这是我试图执行的命令。命令:

**from Flask_Blog import db
db.create_all()
from Flask_Blog import User, Post
user_1 = User(username='Strange', email='doctor@strange.com', password='password')
db.session.add(user_1)
db.session.commit()**

执行提交后,我遇到了错误。

  • 回溯(最后一次调用):文件“C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py”,第 1819 行,在 _execute_context self.dialect.do_execute (文件“C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\engine\default.py”,第 732 行,在 do_execute cursor.execute(语句,参数) sqlite3.IntegrityError: NOT NULL 约束失败:user.image_file 上述异常是以下异常的直接原因: Traceback(最近一次调用最后一次):文件“C:\Users\darjunku\AppData\Local\Programs\Python\Python310\lib \code.py",第 90 行,在 runcode exec(code, self.locals) 文件中"",第 1 行,在文件""中,第 2 行,在提交文件中"C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv \lib\site-packages\sqlalchemy\orm\session.py",第 1435 行,提交 self._transaction.commit(_to_root=self.future) 文件“C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\ lib\site-packages\sqlalchemy\orm\session.py",第 829 行,提交中self._prepare_impl() 文件“C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py”,第 808 行,在 _prepare_impl self.session.flush() 文件中“C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py”,第 3367 行,刷新 self.flush(objects) 文件“C:\Users\darjunku \PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py",第 3506 行,与 util.safe_reraise() 齐平:文件“C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv \lib\site-packages\sqlalchemy\util\langhelpers.py",第 70 行,退出 compat.raise( 文件 "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\ https://sqlalche.me/e/14/gkpj)>\util\compat.py",第 207 行,引发异常文件 "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py",第 3467 行
Traceback (most recent call last):
  File "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1819, in _execute_context
    self.dialect.do_execute(
  File "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\engine\default.py", line 732, in do_execute
    cursor.execute(statement, parameters)
sqlite3.IntegrityError: NOT NULL constraint failed: user.image_file
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "C:\Users\darjunku\AppData\Local\Programs\Python\Python310\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "<string>", line 2, in commit
  File "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 1435, in commit
    self._transaction.commit(_to_root=self.future)
  File "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 829, in commit
    self._prepare_impl()
  File "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 808, in _prepare_impl
    self.session.flush()
  File "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3367, in flush
    self._flush(objects)
  File "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3506, in _flush
    with util.safe_reraise():
  File "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
    compat.raise_(
  File "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
    raise exception
  File "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3467, in _flush
    flush_context.execute()
  File "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 456, in execute
    rec.execute(self)
  File "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 630, in execute
    util.preloaded.orm_persistence.save_obj(
  File "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 245, in save_obj
    _emit_insert_statements(
  File "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 1238, in _emit_insert_statements
    result = connection._execute_20(
  File "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1631, in _execute_20
    return meth(self, args_10style, kwargs_10style, execution_options)
  File "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\sql\elements.py", line 325, in _execute_on_connection
    return connection._execute_clauseelement(
  File "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1498, in _execute_clauseelement
    ret = self._execute_context(
  File "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1862, in _execute_context
    self._handle_dbapi_exception(
  File "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2043, in _handle_dbapi_exception
    util.raise_(
  File "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
    raise exception
  File "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1819, in _execute_context
    self.dialect.do_execute(
  File "C:\Users\darjunku\PycharmProjects\Working_with_Flask\venv\lib\site-packages\sqlalchemy\engine\default.py", line 732, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: user.image_file
[SQL: INSERT INTO user (username, email, image_file, password) VALUES (?, ?, ?, ?)]
[parameters: ('Corey', 'C@demo.com', None, 'password')]
(Background on this error at: https://sqlalche.me/e/14/gkpj)*

回答1

尝试:

image_file = db.Column(db.String(20), nullable=True)

相似文章