Django:1.9 中的用户配置文件

Django: User Profile in 1.9

相关:get user profile in django

上面显示了如何获取用户个人资料,但我了解到已弃用接受的答案方法。

我如何 create/get/use django 1.9 中的用户配置文件?

get_profile() 方法返回有关用户的附加信息。目前,这些信息可以存储在自定义用户模型或与用户模型相关的单独模型中。您可以通过 simply adding one2one relation with User model to your custom User model, or by subclassing the AbstructUserBase model.

子类化用户模型示例:

class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    date_of_birth = models.DateField()
    ...

与用户模型示例的 One2One 关系:

from django.contrib.auth.models import User

class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    department = models.CharField(max_length=100)

models.py

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

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    address = models.TextField()
    ......


def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

每当在 User table 上创建新用户时,以上代码将创建一条 UserProfile 记录。然后您可以访问个人资料详细信息,例如

address = request.user.profile.address