'Django model newly created object from pre_save signal handler disappears
In our Django app, in order to prevent users from randomly updating their profiles for compliance purposes, we need all profile updates to be reviewed. I added a pre_save signal to the User model and in the signal handler, I create an object to the table ProfileUpdateRequest using ProfileUpdateRequest.objects.create(...) and then raise an exception. The exception is then caught in the ViewSet to return a proper response.
However, when I tested it, I found that every time I update the user profile, a new object of ProfileUpdateRequest was created but not applied to the database. I assigned the returned value of the create() method to a variable and logged it out. I saw the id of the new object increasing all the time, but there was no new object added to the table at all.
I wonder whether the changes were not applied to the DB immediately and the exception broke the normal workflow which caused the changes not to be applied to the DB.
@receiver(
models.signals.pre_save,
sender=User,
dispatch_uid='user.request_profile_review',
)
def request_profile_review(instance, **kwargs):
# Only create a request when profile fields have changed.
profile_changed = False
for field in PROFILE_FIELDS: # PROFILE_FIELDS is a list of keys
if instance.tracker.has_changed(field):
profile_changed = True
break
if not profile_changed:
return
updated_profile = extract_profile_from_user(instance)
ProfileUpdateRequest.objects.create(
advisor=instance,
status=1,
profile=updated_profile,
)
raise ComplianceError('Profile update request submitted.')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
