如何在创建用户后立即使用 django 模型 link 用户?

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

我是 Django 的新手,我的问题是如何 link 一个 Django User 和我在用户注册后创建的 Climber 模型?到目前为止,我可以使用 Django 的内置用户注册表注册一个新的 User。但是当我进入我的管理页面时,我看到我必须手动创建一个新的 Climber 和 select,我希望它 User 到 link。提前致谢!

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

你可以用 signals 来做到这一点。

示例:

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, ...)

另一种方法是覆盖User模型的clean()save()方法,考虑到你自己有自定义用户模型。

你应该使用signals

在模型 Climber 中创建函数

@receiver(post_save, sender=User)
def link_climber(sender, instance, created, **kwargs):
    """ If new user is created, create climber for him """
    if created:
        Climber.objects.create(user=instance)