Search code examples
pythondjangodjango-modelsdjango-users

How do I link a User with a django model as soon as the User is created?


I am new to Django and my question is how do I link a Django User with the Climber model that I created as soon as the user is registered? So far, I can register a new User with Django's builtin user registration form. But when I go into my admin page I see that I have to create a new Climber manually and select which User I want it to link to. Thank you in advance!

class Climber(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    grades = [('v'+str(i),'v'+str(i))for i in range(0,13)]
    highest_grade = models.CharField(max_length=3, choices=grades, default='v0')
    team = models.ForeignKey(Team, null=True, on_delete=models.SET_NULL)
    climbs_completed = models.ManyToManyField(Climb, blank=True)

    def __str__(self):
        return self.user.username

    # for each climbs_completed, sum up the points
    def total_score(self):
        pass

Solution

  • You could do this with signals.

    Example:

    from django.contrib.auth import get_user_model
    from django.db.models.signals import post_save
    from django.dispatch import receiver
    from myapp.models import Climber
    
    User = get_user_model()
    
    
    @receiver(post_save, sender=User)
    def my_handler(sender, instance, created, **kwargs):
        if created:
            Climber.objects.create(user=instance, ...)
    

    Another way is to override the clean() or save() method of the User-model, considered that you have a custom user model yourself.