Django:用户档案1.9

时间:2016-01-27 06:51:15

标签: django django-models django-1.9

相关:get user profile in django

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

如何在django 1.9中创建/获取/使用用户个人资料?

2 个答案:

答案 0 :(得分:8)

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)

只要在用户表上创建新用户,上述代码就会创建 UserProfile 记录。然后,您可以访问个人资料详细信息,如

address = request.user.profile.address

答案 1 :(得分:1)

get_profile()方法返回了有关User的其他信息。目前,这些信息可以存储在自定义用户模型中,也可以存储在与用户模型相关的单独模型中。您可以simply adding one2one relation with User model to your custom User modelby 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)