如何使用 AbstractUser 访问自定义用户模型的各个字段?

How to access individual fields with of customised User model using AbstractUser?

我定义了一个从 django.auth.models 继承 AbstractUser 的用户模型。我如何引用该自定义用户模型的每个单独字段?如果我想参考自定义用户的出生日期,我应该写什么?我需要显示用户个人资料,所以在 show_profile.html 文件中,我写道:

first name = {{ settings.AUTH_USER_MODEL.first_name }}
date 0f birth = {{ settings.AUTH_USER_MODEL.dob }}

但是没有用。任何的想法? 此外,我的 url 路线如下所示:

path('my-profile/', views.ProfileView.as_view(), name='my_profile'),

base.html中关注的行是:

<a class="dropdown-item" href="{% url 'my_profile' %}">Edit profile</a>

views.py中的相关行是:

class ProfileView(LoginRequiredMixin, TemplateView):
    template_name = 'show_profile.html'

请指出哪里做错了

您不应该那样访问当前用户信息,因为这是错误的。 settings.AUTH_USER_MODEL 实际上得到的是模型 class 而不是当前用户的对象实例。您应该通过 Django 的上下文处理器通过 request 对象访问它。

在你的 settings.py 上你应该有这样的东西:

TEMPLATES = [
    {
        ...
        'OPTIONS': {
            'context_processors': [
                ...
                'django.template.context_processors.request',
                ...
            ],
        },
    },
]

确保那里有 django.template.context_processors.request,然后要访问当前用户信息,您只需要像这样使用:

first name = {{ request.user.first_name }}
date 0f birth = {{ request.user.dob }}