I’m using Django’s fixtures in my tests. I need to create UserProfile fixture. The first problem is that it’s pointed to User entry. To deal with it, I’m using natural keys. So I just say that UserProfile fixture’s user field is User fixture’s actual username.
[
{
"pk": 8002,
"model": "auth.user",
"fields": {
"date_joined": "2012-08-28 10:00:00.000000+00:00",
"email": "",
"first_name": "",
"groups": [],
"is_active": true,
"is_staff": false,
"is_superuser": false,
"last_login": "2012-08-28 10:00:00.000000+00:00",
"last_name": "",
"password": "pbkdf2_sha256$10000$ltmEKsdCPjuK$74ZwNUh8rqFAPZ6+Cmi3tc8A94ueeXTplFqOQKlY4hc=",
"user_permissions": [],
"username": "user8002"
}
},
{
"pk": null,
"model": "spam_and_eggs.userprofile",
"fields": {
"user": ["user8002"],
"language": "",
"email_activated": true
}
}
]
Unfortunately, it gives back an error:
IntegrityError: Could not load share4you.UserProfile(pk=None): column user_id is not unique
Here comes the second problem. I think that it may fail because UserProfile is automatically created when user is created using Django’s signals and fixture fails because UserProfile for that User is already created. Can it be the reason? Are there any ways to fix it?
Thanks in any advice!
Edit #1:
Model and signal:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
language = models.CharField(max_length=255, null=True, blank=True)
email_activated = models.BooleanField()
@receiver(post_save, sender=User)
def create_profile(instance, created, **kwargs):
if created:
UserProfile.objects.get_or_create(user=instance)
User models is django.contrib.auth.models.User.
Absolutely, if a fixture has a pk which exists in the database, django will do an update.
That is rather interesting, why not a OneToOneField in that case ?
pk=null, set a real integer"user": ["user8002"], you should set"user": 8002.I could not reproduce this behavior. These fixtures can load and reload just fine with your models:
Also, here’s another possibility to make a UserProfile class, with django-annoying: