Django Allauth社交注册报错:UNIQUE constraint failed: auth_profile.user_id
Let me break down what's happening here: You've got two methods working with User profiles—create_or_update_user_profile tied to the User save event, and set_initial_user_names for saving URLs. When a user signs up via the /accounts/social/signup/ route, both methods are likely trying to create a Profile instance for the same User at roughly the same time, which triggers the unique constraint error (since each User can only have one Profile).
Here's how to fix this:
1. Ensure Profile creation uses get_or_create everywhere
The root issue is that one or both of your methods are using Profile.objects.create(...) instead of get_or_create—this method will either fetch an existing Profile or create a new one if it doesn't exist, eliminating duplicate creation attempts.
Update create_or_update_user_profile
Modify your method to prioritize fetching an existing Profile before creating a new one:
def create_or_update_user_profile(sender, instance, created, **kwargs): # Use get_or_create to avoid duplicate Profile creation profile, was_created = Profile.objects.get_or_create(user=instance) if created: # Run initialization logic for new users (if needed) profile.some_default_field = "initial_value" else: # Run update logic for existing users (if needed) profile.last_updated = timezone.now() profile.save()
Update set_initial_user_names
If this method interacts with the Profile, make sure it also uses get_or_create instead of creating a new instance:
def set_initial_user_names(request, user, sociallogin=None, **kwargs): # Your URL saving logic here, e.g.: user_profile_url = sociallogin.account.get_profile_url() # example # Get or create the Profile instead of forcing a new one profile, _ = Profile.objects.get_or_create(user=user) profile.url = user_profile_url profile.save()
2. Check for duplicate signal triggers
Double-check if you've registered the post_save signal for the User model more than once. If both methods are connected to the same signal, that could cause redundant Profile creation attempts. Make sure your signal registration looks clean (only one entry for User save events):
from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User @receiver(post_save, sender=User) def handle_user_save(sender, instance, created, **kwargs): create_or_update_user_profile(sender, instance, created, **kwargs)
3. Verify social auth flow timing
If you're using a library like django-allauth, the social signup flow might trigger multiple User save events. Using get_or_create ensures that even if the User is saved multiple times, the Profile won't be duplicated.
By switching to get_or_create for all Profile-related operations, you eliminate the chance of trying to create two Profiles for the same User—this should resolve the IntegrityError entirely.
内容的提问来源于stack exchange,提问作者Kedinn Turpo

