django成功登录后重定向到home,显示anonymoususer


def loggin(req):
if req.user.is_authenticated:
return redirect('home')
if req.POST:
username=req.POST['username']
password=req.POST['password']
usr = authenticate(req,username=username,password=password)
if usr is not None:
login(req,usr)
return redirect('home')
return render(req,'cart/login.html')
def home(req):
print(req.user.name)
return render(req,'cart/home.html')

我的settings.py很好,我在重定向中使用了反向视图,虽然在登录功能中,我的用户登录了,但因为我想要用户信息在家里显示错误。我不知道我哪里做错了。

req.userUser对象,没有.name属性,但有.username属性,因此:

def home(req):
print(req.user.username)
return render(req,'cart/home.html')

由于__str__方法也返回用户名,因此打印req.user:

可能更方便。
def home(req):
print(req.user)
return render(req,'cart/home.html')

注意在Django中,函数视图的第一个参数通常是request,而不是req

相关内容

最新更新