You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django自定义用户模型关联Ambassadors时触发TransactionManagementError求助

Hey there, let's troubleshoot this TransactionManagementError you're facing when adding a MyUser via the Django admin. I've run into similar transaction-related issues before, so let's break down the most likely causes and fixes based on your scenario.

Common Root Causes

Django's admin wraps object saves in an atomic transaction block by default—this means all database operations during the save are grouped into a single transaction that either completes fully or rolls back entirely. The error you're seeing happens when code tries to perform a database query or transaction operation that conflicts with this ongoing atomic block. Here are the most frequent culprits:

1. Manual Transaction Commits/Rollbacks in Model Save Methods

If your MyUser or Ambassadors model's save() method manually calls transaction.commit() or transaction.rollback(), this will break the admin's atomic block. For example:

# Bad: Manual commit inside save()
class MyUser(AbstractUser):
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        from django.db import transaction
        transaction.commit()  # This triggers the error!

2. Misconfigured Signal Receivers

If you're using a post_save signal to create/update an Ambassadors instance when a MyUser is saved, any transaction-related logic in the signal can cause conflicts. For instance:

# Bad: Manual transaction handling in signal
@receiver(post_save, sender=MyUser)
def create_ambassador(sender, instance, created, **kwargs):
    if created:
        Ambassadors.objects.create(user=instance)
        transaction.commit()  # Unnecessary and problematic

3. Custom Admin save_model Logic

If you've overridden save_model in your MyUserAdmin class, any code that tries to manipulate transactions or perform operations that require an active, uncommitted transaction can trigger the error.

Step-by-Step Fixes

Let's walk through how to resolve each scenario:

  1. Remove Manual Transaction Calls
    Delete any transaction.commit() or transaction.rollback() lines from your model save() methods or signal receivers. The admin's atomic block will handle committing the transaction automatically once all operations are complete.

  2. Fix Signal Logic
    If you're using a signal to link MyUser and Ambassadors, keep the logic simple and transaction-safe. A correct implementation would look like this:

    from django.db.models.signals import post_save
    from django.dispatch import receiver
    
    @receiver(post_save, sender=MyUser)
    def create_ambassador_profile(sender, instance, created, **kwargs):
        if created:
            # This runs inside the admin's atomic block—no manual commit needed
            Ambassadors.objects.create(user=instance)
    
  3. Use transaction.on_commit() for Post-Transaction Operations
    If you need to run code that should only execute after the transaction is successfully committed (like sending an email or calling an external API), wrap it with transaction.on_commit():

    from django.db import transaction
    
    class MyUserAdmin(UserAdmin):
        def save_model(self, request, obj, form, change):
            super().save_model(request, obj, form, change)
            # This code runs ONLY after the admin's transaction is committed
            transaction.on_commit(lambda: send_welcome_email(obj.email))
    

Additional Checks

  • Verify that your Ambassadors model's OneToOneField to MyUser is correctly configured with on_delete=models.CASCADE (or appropriate behavior) to avoid orphaned records.
  • Since you're using Django 2.0.1 (an older version), ensure there are no known transaction-related bugs specific to this version—though the issue is almost certainly in custom code rather than Django itself.

内容的提问来源于stack exchange,提问作者user9252255

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:54:28