0

I have a custom model with a OneToOne relationship with the User (django.contrib.auth.models.User) model;

class Profile(models.Model):
    user = models.OneToOneField(User)

And I want to create a new Profile every time a User is created. So I've added a signal;

@receiver(post_save, sender=User)
def _setup_user(sender, **kwargs):
    """
    Create a new profile instance for each user
    """
    created = kwargs.get('created', False)
    user = kwargs.get('instance', False)
    if created and user:
        profile = Profile(user=kwargs['instance'])
        profile.save()

All this is fine, however syncdb throws an error when creating the admin user because the Profile table has not been created yet (I'm using South to manage migrations).

How can I get around this?

EDIT

So, omitting creating a superuser worked;

$ ./manage.py syncdb --noinput
$ ./manage.py migrate
$ ./manage.py createsuperuser
Kevin
  • 1,113
  • 3
  • 12
  • 26

2 Answers2

1

Run syncdb first and decline making a superuser. Then after creating the db run manage.py createsuperuser

Here's the docs for 1.6

If you have anymore trouble let me know, but if the only issue is that the db isn't created first, then this should work.

Hope it helps

Cheers

wspurgin
  • 2,600
  • 2
  • 17
  • 20
1

You can try something like this:

from django.db import DatabaseError, transaction

@receiver(post_save, sender=User)
@transaction.commit_manually
def _setup_user(sender, **kwargs):
    """
    Create a new profile instance for each user
    """
    created = kwargs.get('created', False)
    user = kwargs.get('instance', False)
    if created and user:
        try:
            profile = Profile(user=kwargs['instance'])
            profile.save()
        except DatabaseError:
            transaction.rollback()
        else:
            transaction.commit()

Depending on your database backend you might not need the manual transaction management, but for psycopg2 it's necessary otherwise you get a "current transaction is aborted" error.

If you take this approach then you'll need to create a profile for the superuser manually after running syncdb, so in that specific case I think that TheSpurg's answer is simpler. It still worth knowing how to recover from a DataBaseError though, so I'm going to post this answer anyway.

Community
  • 1
  • 1
Kevin
  • 959
  • 10
  • 14