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.user
是User
对象,没有.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