[Answered ]-When I try a syncdb, where is the duplicate user_id error coming from?

1👍

You are connecting the User post_save signal twice, because you are importing the account models module on two different paths. This means you are trying to create two user profiles for your new super user, and it fails the second time.

When Django imports the accounts app, the path for the models is accounts.models. However when django imports the pim ‘app’ (it isn’t really an app, it’s the project root, more on that later), the accounts.models module is imported again as pim.accounts.models.

The quickest way to fix the problem is to use a unique identifier when connecting the post save signal.

post_save.connect(create_user_profile, sender = User, dispatch_uid="create_user_profile")

The better fix is to sort out your imports and project layout:

  • create a separate app for your models.py that contains the CalendarEvent model, instead of putting it in your project root.
  • you can name your app ‘pim’ inside your project ‘pim’ if you want
  • move your models.py, admin.py and possibly some if your urls to the new app

If you are currently developing, then the easiest thing to do is to drop the user profile table and let syncdb recreate it. Alternatively you could delete the unneeded user profiles in the shell.

1👍

Note: My previous answer was removed in place of this correct answer…

The issue is that your post_save signal is being connected multiple times every time the accounts.models is imported by anything. What you actually want to do is relocate the signal connection to a management.py file inside your accounts app

accounts/models.py

from django.contrib.auth.models import User
from django.db import models

class UserProfile(models.Model):
    name = models.TextField()
    scratchpad = models.TextField()
    user = models.OneToOneField(User)
    timezone_offset = models.IntegerField(default = 0)


def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user = instance)

accounts/management.py

from django.db.models.signals import post_save
from accounts.models import create_user_profile
from django.contrib.auth.models import User

post_save.connect(create_user_profile, sender = User)

django will load your management.py module one time, so there is now only one signal being connected, regardless of how many times your accounts.models is imported.

👤jdi

Leave a comment