[英]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?我是 Django 的新手,我的问题是如何将 Django User
与我在用户注册后立即创建的Climber
model 链接? So far, I can register a new User
with Django's builtin user registration form.到目前为止,我可以使用 Django 的内置用户注册表单注册一个新User
。 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.但是当我 go 进入我的管理页面时,我看到我必须手动创建一个新的Climber
和 select 我希望它链接到的User
。 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
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.另一种方法是覆盖User
模型的clean()
或save()
方法,考虑到您自己有一个自定义用户 model。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.