1

我是 Django 新手,我的问题是如何将 DjangoUserClimber我在用户注册后创建的模型链接?到目前为止,我可以User使用 Django 的内置用户注册表单注册一个新用户。但是当我进入我的管理页面时,我看到我必须Climber手动创建一个新的并选择User我希望它链接到的。先感谢您!

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
4

2 回答 2

5

你可以用信号做到这一点。

例子:

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

另一种方法是覆盖 -model 的clean()orsave()方法User,考虑到您自己有一个自定义用户模型。

于 2020-05-08T06:58:09.860 回答
1

你应该使用信号

在模型 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)
于 2020-05-08T06:58:54.267 回答