python – Flask SQLAlchemy Unique Column Problems

I want to make a blog where a user can make posts. And I want the title of the post to be unique. But when I try to make a post and the post already exists returns an error. But when I write a try it still returns an error. Why does this happen?

@app.route('/makepost/',methods=['POST','GET'])
@limiter.limit('10 per 10 minutes',cost=ifonly)
def makepost():
    try:
        allposts = Post.query.all()
        sear = 1
        if not current_user.is_authenticated:
            return redirect('/login')
        poster = Users.query.filter_by(name=current_user.name).first()
        if request.method == 'POST':
            title = request.form['title']
            content = request.form['content']
            if len(title) < 5:
                flash("Title must be at least 5")
            if len(title) > 50:
                flash("Title must be 50 characters max")
            if  len(content) < 5:
                flash('Content must be at least 5 letters')
            if len(title) > 5 and len(title) < 50 and len(content) > 5:
                sear = 2
            if sear == 2:
                global post1
                post1 = Post(title=title,content=content,name=current_user.name,author=current_user.id)
                post2 = Post.query.all()    
                db.session.add(post1)
                db.session.commit()
        # error, there already is a user using this bank address or other
        # constraint failed
            if sear != 2:
                    flash('We couldnt make your post')
    except:
        flash('Error')
    return render_template('posts.html')
class Users(UserMixin,db.Model):
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(200),unique=True,nullable=False)
    password = db.Column(db.String(200),unique=False,nullable=False)
    role = db.Column(db.String(200),unique=False,nullable=False)
    missions = db.Column(db.String(200),unique=False,nullable=True)
    waiter = db.Column(db.String(200),unique=False,nullable=False)
    posts = db.relationship('Post',backref="user")

class Post(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    title = db.Column(db.String(200),unique=True,nullable=False)
    content = db.Column(db.Text,unique=False,nullable=False)
    name = db.Column(db.String(200),unique=False,nullable=False)
    date_time = db.Column(db.DateTime(timezone=True),default=datetime.datetime.utcnow())
    author = db.Column(db.Integer,db.ForeignKey('users.id'),unique=False)

This is the full error that I get

Traceback (most recent call last):
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagessqlalchemyenginebase.py", line 1799, in _execute_context
    self.dialect.do_execute(
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagessqlalchemyenginedefault.py", line 717, in do_execute
    cursor.execute(statement, parameters)
sqlite3.IntegrityError: UNIQUE constraint failed: post.title

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagesflaskapp.py", line 2091, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagesflaskapp.py", line 2076, in wsgi_app
    response = self.handle_exception(e)
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagesflaskapp.py", line 2073, in wsgi_app
    response = self.full_dispatch_request()
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagesflaskapp.py", line 1518, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagesflaskapp.py", line 1516, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagesflaskapp.py", line 1502, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagesflask_limiterextension.py", line 1114, in __inner
    self.limiter._check_request_limit(False)
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagesflask_limiterextension.py", line 989, in _check_request_limit
    raise e
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagesflask_limiterextension.py", line 973, in _check_request_limit
    self.__evaluate_limits(endpoint, all_limits)
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagesflask_limiterextension.py", line 930, in __evaluate_limits
    kwargs["cost"] = lim.cost
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagesflask_limiterwrappers.py", line 120, in cost
    return self._cost()
  File "C:UsersuserDesktopPython Fileapp.py", line 161, in ifonly
    db.session.commit()
  File "<string>", line 2, in commit

  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagessqlalchemyormsession.py", line 1428, in commit
    self._transaction.commit(_to_root=self.future)
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagessqlalchemyormsession.py", line 829, in commit
    self._prepare_impl()
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagessqlalchemyormsession.py", line 808, in _prepare_impl
    self.session.flush()
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagessqlalchemyormsession.py", line 3339, in flush
    self._flush(objects)
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagessqlalchemyormsession.py", line 3479, in _flush
    transaction.rollback(_capture_exception=True)
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagessqlalchemyutillanghelpers.py", line 70, in __exit__
    compat.raise_(
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagessqlalchemyutilcompat.py", line 207, in raise_
    raise exception
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagessqlalchemyormsession.py", line 3439, in _flush
    flush_context.execute()
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagessqlalchemyormunitofwork.py", line 456, in execute
    rec.execute(self)
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagessqlalchemyormunitofwork.py", line 630, in execute
    util.preloaded.orm_persistence.save_obj(
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagessqlalchemyormpersistence.py", line 242, in save_obj
    _emit_insert_statements(
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagessqlalchemyormpersistence.py", line 1219, in _emit_insert_statements
    result = connection._execute_20(
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagessqlalchemyenginebase.py", line 1611, in _execute_20
    return meth(self, args_10style, kwargs_10style, execution_options)
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagessqlalchemysqlelements.py", line 323, in _execute_on_connection
    return connection._execute_clauseelement(
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagessqlalchemyenginebase.py", line 1478, in _execute_clauseelement
    ret = self._execute_context(
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagessqlalchemyenginebase.py", line 1842, in _execute_context
    self._handle_dbapi_exception(
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagessqlalchemyenginebase.py", line 2023, in _handle_dbapi_exception
    util.raise_(
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagessqlalchemyutilcompat.py", line 207, in raise_
    raise exception
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagessqlalchemyenginebase.py", line 1799, in _execute_context
    self.dialect.do_execute(
  File "C:UsersuserAppDataLocalPackagesPythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0LocalCachelocal-packagesPython39site-packagessqlalchemyenginedefault.py", line 717, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: post.title
[SQL: INSERT INTO post (title, content, name, date_time, author) VALUES (?, ?, ?, ?, ?)]
[parameters: ('aaaaaaa', 'aaaaaaa', 'fffff', '2022-05-06 12:48:20.043379', 1)]
(Background on this error at: https://sqlalche.me/e/14/gkpj)
127.0.0.1 - - [06/May/2022 15:48:34] "GET /makepost/?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
127.0.0.1 - - [06/May/2022 15:48:34] "GET /makepost/?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
127.0.0.1 - - [06/May/2022 15:48:34] "GET /makepost/?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -
127.0.0.1 - - [06/May/2022 15:48:34] "GET /makepost/?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
127.0.0.1 - - [06/May/2022 15:48:34] "GET /makepost/?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -

I get this error in the browser and in the console log.

Please answer.

Thanks.

Leave a Comment