django:通过一对一链接扩展用户模型-如何使用post_save信号

时间:2018-07-21 16:42:30

标签: django

我是django的新手,正在学习如何使用以下站点扩展用户模型: https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html

我对以下模型有疑问:

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

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)

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

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

此行的工作原理:

        Profile.objects.create(user=instance)

我知道创建用户后将调用post_save,但是我不明白如何使用以下行来存储其他字段。

        Profile.objects.create(user=instance)

0 个答案:

没有答案