简体   繁体   中英

sqlalchemy.exc.IntegrityError

 sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: post.user_id
[SQL: INSERT INTO post (title, content, date_created, user_id) VALUES (?, ?, ?, ?)]
[parameters: ('dsaglhfl', 'sijd;avbvjab', '2020-08-22 09:50:09.983189', None)]
(Background on this error at: http://sqlalche.me/e/gkpj)

I do not understand why this error occurs. The code for databses is below:

    class User(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)
        username = db.Column(db.String(20), nullable=False, unique=True)
        email = db.Column(db.String(50), nullable=False)
        password = db.Column(db.String(60), nullable=False)
        image_file = db.Column(db.String(60), nullable=False,
                       default='default.jpg')
        posts = db.relationship('Post', backref='author', lazy=True)

        def __repr__(self):
            return f'{self.username}'

   class Post(db.Model):
       id = db.Column(db.Integer, primary_key=True)
       title = db.Column(db.String(100), nullable=False)
       content = db.Column(db.Text, nullable=False)
       date_created = db.Column(
                    db.DateTime, nullable=False, default=datetime.utcnow)
       user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

       def __repr__(self):
          return f'{self.title}'

And also the route

    @app.route('/post/new', methods=['GET', 'POST'])
    @login_required
    def new_post():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data, content=form.content.data)
        db.session.add(post)
        db.session.commit()
        flash('Your post was added!', 'success')
        return redirect(url_for('home'))
    return render_template('create_post.html', form=form, title='New Pos', heading='New Post')

What shoul I change so this could work.Ishould mention that I used the same code in the past and it worked

Based on your model, field user_id is required, because the parameter is given nullable=False .

You must fill in this field and other required fields that also have nullable=False or set nullable=True for optional fields.

Crazyzubr is correct, the issue is how you're instantiating the Post() object:

        post = Post(title=form.title.data, content=form.content.data)
        db.session.add(post)

You never set post.user_id prior to adding it to the session, so you'll fail the NOT NULL constraint in your Post model:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM