I get the error (sqlite3.IntegrityError) NOT NULL constraint failed: quiz1.user_id when I try saving to my table a second time. The tables are defined in my models.py file as:
class User(db.Model, UserMixin): 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.jpg') password = db.Column(db.String(60), nullable=False) posts = db.relationship('Post', backref='author', lazy=True) quiz = db.relationship('Quiz1', backref='author', uselist=False) 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) class Quiz1(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) q1ans = db.Column(db.String(20), nullable=False) q2ans = db.Column(db.String(20), nullable=False) q3ans = db.Column(db.String(20), nullable=False) q4ans = db.Column(db.String(20), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) In my routes.py file I have
@posts.route("/quiz", methods=['GET', 'POST']) @login_required def taste_quiz(): form = QuizForm() if form.validate_on_submit(): quiz = Quiz1(q1ans=form.q1ans.data, q2ans=form.q2ans.data, q3ans=form.q3ans.data, q4ans=form.q4ans.data, author=current_user) db.session.add(quiz) db.session.commit() flash('Your responses have been saved', 'success') return redirect(url_for('main.home')) return render_template('taste_quiz.html', form=form) When I click submit on the quiz form for the first time, the code executes as expected. When I try to submit it again it gives me the NOT NULL constraint failed error:
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: quiz1.user_id [SQL: INSERT INTO quiz1 (q1ans, q2ans, q3ans, q4ans, user_id) VALUES (?, ?, ?, ?, ?)] [parameters: ('3', '4', '5', '6', None)] (Background on this error at: http://sqlalche.me/e/13/gkpj) If I delete the record manually from the database and then submit the quiz form again, it works as expected but then trying it another time causes it to fail again.
If there is more code that you need to see, please let me know and I will update the question.
Thanks in advance
https://stackoverflow.com/questions/65605138/saving-to-table-works-first-time-but-not-second-time-results-in-error-not-null January 07, 2021 at 08:33AM
没有评论:
发表评论