'Change IntegratyError page on Flask and SQLAlchemy

I'm doing a rental system with Flask and I have some registers on a data base like Tenant, Owner and Immobile with their primary key and some foreign keys.

When I try to clear a table with a foreign key I have this IntegrityError:

IntegratyError

But I don't want to solve this error, I just want to change this page to another. How could I do that?

This is my code:

@app.route('/inquilino_delete/<id>', methods=['GET', 'POST'])
def inquilino_delete(id):
    inquilino = Inquilino.query.get_or_404(id)
    print(id)
    if request.method == 'GET':
        return render_template('inquilino/delete_inquilino.html', inquilino=inquilino)
    if request.method == 'POST':
        if inquilino:
            db.session.delete(inquilino)
            db.session.commit()
            
            return redirect(url_for('show_all_inquilinos'))
        abort(404)


Solution 1:[1]

I got it with a try except sqlalchemy.exc import IntegrityError

def inquilino_delete(id):
    inquilino = Inquilino.query.get_or_404(id)
    print(id)
    
    if request.method == 'GET':
        return render_template('inquilino/delete_inquilino.html', inquilino=inquilino)
    if request.method == 'POST':
        if inquilino:
            db.session.delete(inquilino)
            try:
                db.session.commit()
                return redirect(url_for('show_all_inquilinos'))
            except IntegrityError:
                flash('Você não pode excluir por ser uma chave estrangeira!')
                return redirect(url_for('show_all_inquilinos'))
        abort(404)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Todeshine