简体   繁体   English

如何在 Django 中获取登录用户的用户名?

[英]How can I get the username of the logged in user in Django?

I'M new to Django, looking to get first name and last name of the logged-in user in Django, login method am using LDAP authentication.我是 Django 的新手,希望在 Django 中获取登录用户的名字和姓氏,登录方法是使用 LDAP 身份验证。

when i login as admin i was able to see the LDAP user in User information tab.当我以管理员身份登录时,我能够在用户信息选项卡中看到 LDAP 用户。

Tried request.user.first_name didn't work, is there any other method to get the details?试过 request.user.first_name 没有用,还有其他方法可以获取详细信息吗?

You can use this method to get first name, last name and all details of the logged in user.您可以使用此方法获取登录用户的名字、姓氏和所有详细信息。

from django.contrib.auth.models import User
first_name = User.objects.get(username=request.user).first_name
last_name = User.objects.get(username=request.user).last_name

In the same way you can get any attribute of the user.以同样的方式,您可以获得用户的任何属性。 For logged in users, you have to use the keyword request.user .对于登录用户,您必须使用关键字request.user

There is two method in AbstractUser class, you can use this AbstractUser class 中有两种方法,你可以使用这个

request.user.get_full_name()
request.user.get_short_name()

get_short_name will return first_name get_short_name 将返回 first_name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Django 中获取登录用户的用户名? - How can I get the username of the logged-in user in Django? 如何在Django views.py中获取登录用户的用户名 - How can I get the username of the logged-in user in Django views.py 如何获取写入文本的登录用户的用户名并将其永久显示在 Django 中的文本旁边? - How do i get the username of a logged user writing a text and display it beside the text permanently in Django? Django:如何在基于 class 的视图中获取登录用户的用户名? - Django: How do I get the username of the logged-in user in my class based view? Django:如何在视图请求之外获取登录用户? - Django: How can i get the logged user outside of view request? 如何将django中当前登录的用户配置文件添加到模型中? - How can I get current logged user profile in django, into models? 如何将登录用户的用户名添加到 django 中的模型字段 - How do I add username of logged in user to model field in django Django 获取登录用户的用户名并将其传递给模型 - Django get username of logged in user and pass it to models 如何从 django 用户模型中获取用户名 - How can I get a username from django User Model 如果登录Django,如何获取用户ID? - How I get User ID if logged in Django?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM