获取vi中的当前用户

2024-04-27 18:30:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用django身份验证登录用户:

def signin(request):
        if request.method == "POST":
                username = request.POST.get("username").lower()
                password = request.POST.get("password").lower()
                user = authenticate(username = username, password=password)

但是,我似乎无法在任何其他视图中访问当前用户。在每个模板中,我都可以访问用户,但在视图本身中似乎无法访问。例如,在另一个路由中,我希望能够执行以下操作:

def profile(request):
        skills = hasSkill.objects.filter(user__username=user.username)
        return render(request, "/profile.html", {"skills" : skills})

但我一直有一个错误,用户是非类型对象。有什么想法吗?


Tags: django用户身份验证视图getrequestdefusername
1条回答
网友
1楼 · 发布于 2024-04-27 18:30:10

您需要通过获得的request访问user。您将使用request.user将视图更改为:

def profile(request):
        skills = hasSkill.objects.filter(user__username=request.user)
        return render(request, "/profile.html", {"skills" : skills})

Django文档herehere

Django uses sessions and middleware to hook the authentication system into request objects.

These provide a request.user attribute on every request which represents the current user. If the current user has not logged in, this attribute will be set to an instance of AnonymousUser, otherwise it will be an instance of User.

相关问题 更多 >