提取已登录的用户详细信息时出错 [英] Error when fetching the logged in user details

查看:56
本文介绍了提取已登录的用户详细信息时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django 2.2.6.

I am using Django 2.2.6.

登录代码

class loginController(View):
    def post(self, request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        userobj = authenticate(username = username, password = password)
        if(userobj != None):
            login(request, userobj)
            return redirect('myprofileapp:profile')

用户通过身份验证后,导航至个人资料页面.当此行执行 if(request.user.is_authenticated):时,出现错误.

Once the user is authenticated, navigated to profile page. When this line executes if(request.user.is_authenticated):, I get an error.

class accountController(View):
    def get(self, request):
        if(request.user.is_authenticated):
            return HttpResponse(request.user)

用户"对象不可迭代

'User' object is not iterable

编辑1

class accountController(View):
    def get(self, request):
        if(request.user.is_authenticated):
            print(request.user.username)
            return HttpResponse("ok")
        else:
            return HttpResponse("not ok")

不打印任何内容.好的,可以在上面的代码中打印出来.

nothing is printed. Just ok got printed in above code.

推荐答案

这是错误的:

return HttpResponse(request.user)

您可以将字符串传递给 HttpResponse .您正在传递 request.user ,它是一个对象.由于用户名是字符串,因此您可以执行以下操作:

You can pass in a string to HttpResponse. You are passing request.user which is an object. Since the user name is a string you can do something like:

return HttpResponse( request.user.username)

基本上,您传递给 HttpResponse 的任何字符串都将显示在浏览器中.您通过确定",确定将被打印,您通过"Pankaj",Pankaj被打印.您传递作为字符串的 request.user.username ,该用户名将在浏览器中显示为响应.

Basically whatever string you pass to HttpResponse will be shown in in the browser. You pass "ok", ok will be printed, you pass "Pankaj", Pankaj gets printed. You pass request.user.username which is a string, that username gets shown in the browser as response.

print 中放入一些内容会打印到django控制台,而不会打印到您的Web浏览器.

Putting something in print prints to your django console, it does not print to your web browser.

这篇关于提取已登录的用户详细信息时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆