'sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: student.email
I have a registration form and am trying to add student data to the database model(Student) but i get this error upon submiting the form data
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: student.email
[SQL: INSERT INTO student (username, email, image_file, password) VALUES (?, ?, ?, ?)]
[parameters: ('elijah', '[email protected]', 'default.jpg', '$2b$12$lo4MLsE/hdI6SOnUr3lg5eg02u.u5xfRJYwKQzMn3bohXglif/73S')]
(Background on this error at: https://sqlalche.me/e/14/gkpj)
Am not sure of what's causing the error, have tried dropping and recreating my database modles again but the error persists.
This is my student model where the error is pointing to student.email
from datetime import datetime
from ..utils.db import db
class Student(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(255), nullable=True, default='default.jpg')
password = db.Column(db.String(120), nullable=False)
student_mark = db.relationship('Mark', backref='mark')
student_qn = db.relationship('StudentQuestion',backref='examinee')
def __repr__(self):
return f"Student('{self.username}', '{self.email}')"
def save(self):
db.session.add(self)
db.session.commit()
and this is the route that has the submission form which throws the error after i insert data into the form
from flask import render_template, url_for, flash, redirect, Blueprint
from .registerform import RegistrationForm
from flask_bcrypt import Bcrypt
from ..models.models import Student
from ..utils.db import db
bcrypt = Bcrypt()
register_route = Blueprint('register_route', __name__)
@register_route.route('/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
student= Student(username=form.username.data, email=form.email.data, password=hashed_password)
db.session.add(student)
db.session.commit()
flash(f'Welcome {form.username.data} ,your can now login!')
return redirect(url_for('login_route.login'))
return render_template('register.html', title='RegisterPage', form=form)
What could be the problem and how can i avoid it!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
