【问题标题】:sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: user.idsqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL 约束失败:user.id
【发布时间】:2021-07-02 16:01:47
【问题描述】:

当我尝试将数据添加到数据库时出现错误。我已经建立了数据库和它的应用程序

class User(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(120),nullable = False)
    email = db.Column(db.String(70),primary_key=True,nullable = False)
    post = db.Column(db.String(10000),default ="")
    date_created = db.Column(db.DateTime, default = datetime.utcnow)

    def __repr__(self):
        return f'{self.id},{self.name},{self.email},{self.post},{self.date_created}'

每当我尝试在下面的代码中创建数据库时都会遇到问题:

@app.route('/sign_up',methods = ["POST","GET"])
def sign_up():
    if request.method == 'POST':
        email = request.form.get('email')
        first_name = request.form.get('first_name')
        password_1 = request.form.get('password')
        password_2 = request.form.get('password-2')

        user = User.query.filter_by(email=email).first()

        if user:
            flash("Email aleady exists", category = 'error')
        elif len(email) < 5:
            flash("Email name must be greater than 5 characters", category='error')
        # We'll come back to you tomorrow (i.e 25th March)
        elif len(first_name) < 2:
            flash("First Name too short",category='error')
        elif password_1 != password_2:
            flash("Make sure you typed the password correctly",category='error')
        elif len(password_1) < 8:
            flash("Make sure your password as at least 8 characters", category='error')
        else:
            new_user = User(name= first_name,email = email)
            db.session.add(new_user)
            db.session.commit()
            flash("Account Created",category='success')
            return redirect(url_for('home'))

    return render_template("sign-up.html")

【问题讨论】:

  • sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL 约束失败:user.id [SQL: INSERT INTO user (name, email, post, date_created) VALUES (?, ?, ?, ?)] [参数:('test', 'presidentdavid@gmail.com', '', '2021-04-06 20:10:03.191785')] (此错误的背景:sqlalche.me/e/14/gkpj)。我得到的错误
  • 在问题中将回溯显示为格式正确的文本,而不是评论。显示导致回溯的代码(在问题中正确格式化)。不要只谈论“问题”。会发生什么,应该发生什么?
  • 对不起...大声笑...这是我的第一个问题仍然掌握它...会尝试重新编辑它

标签: python sqlite flask sqlalchemy flask-sqlalchemy


【解决方案1】:

在 Postgresql 中更新表。使 ID 自动递增

或为 id 提供数据(已弃用)

【讨论】:

  • 谢谢..我尝试了自动增量..它没有工作..我不太明白为 Id 提供数据
猜你喜欢
  • 1970-01-01
  • 2022-08-10
  • 2021-08-07
  • 2021-06-29
  • 2021-06-12
  • 1970-01-01
  • 2023-03-20
  • 2023-03-29
  • 1970-01-01
相关资源
最近更新 更多