【问题标题】:How to access individual fields with of customised User model using AbstractUser?如何使用 AbstractUser 访问自定义用户模型的各个字段?
【发布时间】:2020-06-11 14:06:36
【问题描述】:

我定义了一个从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在你的show_profile.html上显示什么?
  • show_profile.html 显示用户的个人资料。
  • show_profile.html 中的一些行是:名字 = {{ settings.AUTH_USER_MODEL.first_name }} 日期 0f 出生 = {{ settings.AUTH_USER_MODEL.dob }}

标签: django django-templates django-context


【解决方案1】:

您不应该像那样访问当前用户信息,因为这是错误的。 settings.AUTH_USER_MODEL 实际上得到的是模型类而不是当前用户的对象实例。您应该通过 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 }}

【讨论】:

  • 好的,知道了。但是我应该在 urls.py 文件中写什么?我写道:路径('my-profile//',views.ProfileView.as_view(),name='my_profile')。这个可以吗。访问个人资料页面的链接再次写为:编辑个人资料。这也行吗。请指教。
  • @SandipNath 您应该使用 url 路径的名称并在必要时包含其命名空间{% url 'my_profile' request.user.pk %},如果有一些混淆,请检查the docs
  • @SandipNath 很高兴我能帮上忙!如果还有其他事情,我可以帮忙 ping!如果您认为这是一个好的答案,请考虑投票;D
  • 非常感谢贝尔纳多。但是还有一个小问题,就是在模板文件中写request.user.picture,显示的是图片的文件名,而不是图片本身。图片而不是名字怎么显示?
  • @SandipNath 您目前如何显示图片?
猜你喜欢
  • 1970-01-01
  • 2013-07-02
  • 2022-12-12
  • 2021-07-24
  • 1970-01-01
  • 1970-01-01
  • 2012-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多