Home > Software engineering >  UNIQUE constraint failed (SQLAlchemy)
UNIQUE constraint failed (SQLAlchemy)

Time:10-24

My flask app is throwing an error when I use db.commit.session(). I don't see where the fault is in my code. This is the code in the terminal and the error:

>>> user_1 = User(username='Corey', email='C@demo.com', password='password')
>>> db.session.add(user_1)
>>> user_2 = User(username='JohnDoe', email='jd@demo.com', password='password')
>>> db.session.add(user_2)
>>> db.create_all()
>>> db.session.commit()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 2, in commit
  File "C:\Users\hp\miniconda3\lib\site-packages\sqlalchemy\orm\session.py", line 1428, in commit
    self._transaction.commit(_to_root=self.future)
  File "C:\Users\hp\miniconda3\lib\site-packages\sqlalchemy\orm\session.py", line 827, in commit
    self._assert_active(prepared_ok=True)
  File "C:\Users\hp\miniconda3\lib\site-packages\sqlalchemy\orm\session.py", line 608, in _assert_active
    code="7s2a",
sqlalchemy.exc.PendingRollbackError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (sqlite3.IntegrityError) UNIQUE constraint failed: user.image_file
[SQL: INSERT INTO user (username, email, image_file, password) VALUES (?, ?, ?, ?)]
[parameters: ('JohnDoe', 'jd@demo.com', 'default.jpg', 'password')]
(Background on this error at: https://sqlalche.me/e/14/gkpj) (Background on this error at: https://sqlalche.me/e/14/7s2a)

Honestly I don't know if it's my code from the terminal or my main code.

This is the code from my app:

from datetime import datetime
from flask import Flask, render_template, url_for, flash, redirect
from flask_sqlalchemy import SQLAlchemy
from forms import RegistrationForm, LoginForm
 
app = Flask(__name__)
app.config['SECRET_KEY'] = 'cac78a5498388aa4a95fb2be0f0a6499'
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), unique=True, default='default.jpg')
    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}')"

CodePudding user response:

The problem is that you are defining the user model's column image_file as 'unique' when you specify unique=True. This then throws an error when you create a new user(without specifying an image_file), because the default image_file is always 'default.jpg'. Basically, you will just need to remove the unique=True attribute in the image_file column, as new users will (by default) have the same image file.

  • Related