How to retrieve the currently logged in user in Django?
In Django, you can access the current logged-in user by using the user attribute of the request object. The specific steps are as follows:
- Make sure to have the django.contrib.auth application configured, and add django.contrib.auth.middleware.AuthenticationMiddleware to the MIDDLEWARE setting.
- In a view function or method, the current request object can be accessed through the request parameter.
- You can access the currently logged-in user object using request.user.
The sample code is shown below:
from django.shortcuts import render
def my_view(request):
if request.user.is_authenticated:
# 获取当前登录的用户名
username = request.user.username
# 获取当前登录的用户对象
user = request.user
# 其他操作...
return render(request, 'my_template.html', {'username': username})
else:
# 用户未登录的操作...
return render(request, 'login.html')
In the above example, we use request.user.is_authenticated to check if the user is logged in. If the user is logged in, we can access the current user object through request.user and perform relevant actions; if the user is not logged in, we can handle accordingly (such as redirecting to the login page).
Note that after configuring the django.contrib.auth application, Django will automatically add the request.user property to every request, so manual addition is not necessary.