user24353 user24353 - 3 months ago 12
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 models.py:

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 self.pk:
hash = gen_hash(self.id, 30)
while SocialProfile.objects.filter(hash=hash).exists():
hash = gen_hash(self.id, 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)

SocialProfile.objects.count()


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!

Answer

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 self.pk:
        ...
    return super(SocialProfile, self).save(*args, **kwargs)