Shohanul Alam Shohanul Alam - 5 months ago 37
Python Question

django creating a row in userprofile table when a user is created

I am following this(https://www.django-tips.com/tutorial/django-tutorial-with-twitter-app/1/?page=3) tutorial to create a twitter clone app with django. But in the project, user will be created through the django default user creation system.

The problem is, I want to create a row in userprofile table when a user is created. Otherwise the user is creating and I have to insert it in the userprofile table bu accessing the admin section of the project. How can I do this?

the model looks like this:

from django.contrib.auth.models import User

class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
relation = models.ManyToManyField(
'self',
through='Relation',
symmetrical=False,
related_name='related_to',
default=None
)
def __unicode__(self):
return self.user.get_full_name()

class Relation(models.Model):
follower = models.ForeignKey(UserProfile, related_name='follows')
is_followed = models.ForeignKey(UserProfile, related_name='followers')
follow_time = models.DateTimeField(auto_now_add=True)

def __unicode__(self):
return '%s follows %s' % (self.follower.user.username, self.is_followed.user.username)

class Meta:
unique_together = ('follower', 'is_followed')


And the tutorial also mentioned to create a signal but they haven't cleared where this file will be created, so I have followed the official doc and created the signals.py file.

def create_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=user)
post_save.connect(create_profile, sender=User)


So, I am stuck at this stage and I can't move forward. Thanks in advance.

Answer

you don't have to create signals file... just after the UserProfile

from django.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class UserProfile(models.Model):
    ....

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)
Comments