Django 的文档说明了一切,特别是 Storing additional information about users 部分。首先,您需要在 models.py 的某处定义一个模型,其中包含用户附加信息的字段:
models.py
from django.contrib.auth.models import User
class UserProfile(models.Model):
# This field is required.
user = models.OneToOneField(User)
# Other fields here
accepted_eula = models.BooleanField()
favorite_animal = models.CharField(max_length=20, default="Dragons.")
然后,您需要通过在您的settings.py 中设置AUTH_PROFILE_MODULE 来表明此模型(UserProfile)是用户配置文件:
settings.py
...
AUTH_PROFILE_MODULE = 'accounts.UserProfile'
...
您需要将accounts 替换为您的应用名称。最后,您希望在每次创建 User 实例时通过注册 post_save 处理程序来创建配置文件,这样每次创建用户时 Django 也会创建他的配置文件:
models.py
from django.contrib.auth.models import User
class UserProfile(models.Model):
# This field is required.
user = models.OneToOneField(User)
# Other fields here
accepted_eula = models.BooleanField()
favorite_animal = models.CharField(max_length=20, default="Dragons.")
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
访问个人资料
要在您的视图中访问当前用户的个人资料,只需使用请求提供的User 实例,并在其上调用get_profile:
def your_view(request):
profile = request.user.get_profile()
...
# Your code