且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Django 中获取用户个人资料

更新时间:2023-02-12 19:54:33

Django 的文档说明了一切,特别是 存储关于用户的附加信息.首先,您需要在 models.py 中的某处定义一个模型,其中包含用户附加信息的字段:

Django's documentation says it all, specifically the part Storing additional information about users. First you need to define a model somewhere in your models.py with fields for the additional information of the user:

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) 是用户配置文件:

Then, you need to indicate that this model (UserProfile) is the user profile by setting AUTH_PROFILE_MODULE inside your settings.py:

settings.py

...
AUTH_PROFILE_MODULE = 'accounts.UserProfile'
...

您需要将 accounts 替换为您的应用程序名称.最后,您希望在每次通过注册 post_save 处理程序创建 User 实例时创建一个配置文件,这样每次创建用户时,Django 也会创建他的配置文件:

You need to replace accounts with the name of your app. Finally, you want to create a profile every time a User instance is created by registering a post_save handler, this way every time you create a user Django will create his profile too:

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 就可以了:

Accessing the Profile

To access the current user's profile in your view, just use the User instance provided by the request, and call get_profile on it:

def your_view(request):
    profile = request.user.get_profile()
    ...
    # Your code