Shawky Ahmed
Shawky Ahmed

Reputation: 35

SQLAlchemy querying the wrong table using route

I'm trying to pass a user_id through the below form action button

<form action="{{ url_for('users.user_delete', user_id=user.id)}}" method="POST">
     <input type="submit" class="btn btn-danger" value="Delete">
</form>

then i'm using the below route to query the user and delete from db

@users.route("/user/<int:user_id>/delete",methods=['POST'])
@login_required
def user_delete(user_id):
   user = User.query.filter_by(id=user_id).first()
   db.session.delete(user)
   db.session.commit()
   flash("User has been deleted", "success")
   return redirect(url_for('users.admin_panel'))

However, for some reason, it is querying the other table and this is the error:

sqlalchemy.exc.IntegrityError sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: post.user_id [SQL: UPDATE post SET user_id=? WHERE post.id = ?] [parameters: (None, 2)] (Background on this error at: http://sqlalche.me/e/gkpj)

Upvotes: 1

Views: 348

Answers (1)

Joost
Joost

Reputation: 3729

You cannot delete a user if it still has posts connected to it, because the posts won't have an author which is prohibited by your Post model. You can prevent this by first deleting the users posts and then the user, or by setting nullable parameter to True at the user_id column in the Post model

I think thank something like this should work:

user = User.query.filter_by(id=user_id).first()
db.session.delete(user.posts)
db.session.delete(user)
db.session.commit()

Upvotes: 1

Related Questions