I'm trying to make it so that when a User model is created, it also creates the corresponding MyAppProfile class to go with it. But when I do so, as I've seen online, I get an error.
An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.
I've tried various methods to do this, and they give that error when I try it. I can't figure out why I'm getting that error, or where exactly it's coming from.
My profile class:
class MyAppProfile(models.Model):
user = models.OneToOneField(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="myapp_profile")
# Other fields for this app's profile go here
def __str__(self):
return f'{self.id}: MyApp Profile for {self.user.username}'
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
@receiver(post_save, sender=AUTH_USER_MODEL)
def update_profile_signal(sender, instance, created, **kwargs):
if created:
MyAppProfile.objects.create(user=instance)
instance.myapp_profile.save()
Edit:
My user model:
class User(AbstractUser):
id = UUIDField()
def save(self, *args, **kwargs):
if not self.pk:
saved = False
attempts = 0
while not saved:
try:
if attempts > 5:
raise RuntimeError('Max attempts reached trying to save to database.')
super().save(*args, **kwargs)
except IntegrityError:
attempts += 1
self.id = gen_uuid(length=8)
question from:
https://stackoverflow.com/questions/65868724/transactionmanagementerror-when-saving-model-with-onetoone-relationship-in-djang 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…