user24353 user24353 - 5 months ago 19
Python Question

django model create does not work

I added a new model to my app named SocialProfile, which is responsible for keeping social-related properties of a user which has a one-to-one relationship with UserProfile model. This is the SocialProfile model in

class SocialProfile(models.Model):
profile = models.OneToOneField('UserProfile', on_delete=models.CASCADE)
facebook_profiles = models.ManyToManyField('FacebookContact', related_name='synced_profiles', blank=True)
google_profiles = models.ManyToManyField('GoogleContact', related_name='synced_profiles', blank=True)
hash = models.CharField(max_length=30, unique=True, blank=True)

def save(self, *args, **kwargs):
if not
hash = gen_hash(, 30)
while SocialProfile.objects.filter(hash=hash).exists():
hash = gen_hash(, 30)
self.hash = hash

def __str__(self):
return str(self.profile)

Right now, I keep a record for synced facebook & google profiles. Now, the problem is that creating new objects does not actually add any record in the database. I cannot create instances with scripts or admin. In case of scripts, the following runs without errors but no record is created:

for profile in UserProfile.objects.all():
sp = SocialProfile.objects.create(profile=profile)
print(profile, sp)


The prints are done, and look correct and the count() returns 0. I try creating objects in admin, but I get the following error:

"{{socialprofile object}}" needs to have a value for field "socialprofile" before
this many-to-many relationship can be used.

I think that is another problem, because if I comment the Many-to-Many relationships, it is done, without error (still no new records). I mentioned it just if it might help.

I have checked the database, the tables are there, no new migrations are detected either.

Any help and idea about what could be the problem would be appreciated!


You've overwritten the save method so that it never actually saves anything. You need to call the superclass method at the end:

def save(self, *args, **kwargs):
    if not
    return super(SocialProfile, self).save(*args, **kwargs)