Skip to content

fix: prevent IntegrityError when deleting user account#2234

Closed
Simon99 wants to merge 1 commit intowger-project:masterfrom
Simon99:fix/user-deletion-statistics
Closed

fix: prevent IntegrityError when deleting user account#2234
Simon99 wants to merge 1 commit intowger-project:masterfrom
Simon99:fix/user-deletion-statistics

Conversation

@Simon99
Copy link

@Simon99 Simon99 commented Mar 2, 2026

Summary

Fixes the IntegrityError that occurs when a user deletes their account.

Problem

When a user deletes their account, Django cascades the deletion to related objects (WorkoutLog, WorkoutSession). The post_delete signal handlers try to recalculate user statistics, but the user no longer exists at that point, causing an IntegrityError:

IntegrityError: insert or update on table "trophies_userstatistics" 
violates foreign key constraint "trophies_userstatistics_user_id_0de72480_fk_auth_user_id"
DETAIL: Key (user_id)=(....) is not present in table "auth_user".

Solution

Added User.DoesNotExist checks in both delete signal handlers before attempting to update statistics:

  • workout_log_deleted() - checks if user exists before recalculating
  • workout_session_deleted() - checks if user exists before recalculating

If the user has been deleted, we skip the statistics update and log a debug message.

Changes

  • Modified wger/trophies/signals.py
    • Added User existence check in workout_log_deleted
    • Added User existence check in workout_session_deleted
    • Added debug logging when skipping updates for deleted users

Testing

The fix handles the race condition where:

  1. User deletion triggers cascade deletion of logs/sessions
  2. Delete signals fire for each deleted object
  3. Signal handlers check if user still exists
  4. If user is deleted, skip statistics update gracefully

Fixes

Fixes #2232

Check if user exists before updating statistics in delete signal handlers.
This prevents IntegrityError when workout logs/sessions are deleted as
part of user deletion cascade.

When a user deletes their account, Django cascades the deletion to
related objects (WorkoutLog, WorkoutSession). The post_delete signals
try to recalculate statistics, but the user no longer exists, causing
an IntegrityError on the foreign key constraint.

Solution: Check User.DoesNotExist before calling statistics service.

Fixes wger-project#2232
@rolandgeider
Copy link
Member

hey thanks for the PR!

however somebody else had already started working on this in #2233 (it seems they started half an hour before you) so I'll close this PR, sorry

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug when deleting user

2 participants