我似乎不知道如何在 Django 中登录用户。我很困惑,因为文档明确地告诉你如何去做,但不知何故我一定是犯了一个错误。
链接 https://docs.djangoproject.com/en/dev/topics/auth/default/#django.contrib.auth.login 说“要从视图中登录用户,请使用 login()。它需要一个HttpRequest 对象和一个 User 对象。login() 在会话中保存用户的 ID,使用 Django 的会话框架。”
所以我有以下views.py:
def login_view(request):
if request.method == 'GET':
return render(request, 'app/login.htm')
if request.method == 'POST':
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is None:
return HttpResponseRedirect(reverse('error'))
if not user.is_active:
return HttpResponseRedirect(reverse('error'))
# Correct password, and the user is marked "active"
auth.login(request, user)
# Redirect to a success page.
return HttpResponseRedirect(reverse('home'))
def home(request):
contextdict = {}
if request.session.user.is_authenticated():
contextdict['username'] = request.session.user.username
context = RequestContext(request, contextdict )
return render(request, 'app/home.htm', context)
Run Code Online (Sandbox Code Playgroud)
现在,通过使用 print 'qqq' 我知道'is None' 和 'not is_active' 已被评估为 True,因此评估 auth.login 并返回 HttpResponseRedirect。我希望一切正常,用户登录,用户名作为主视图中的上下文传递。但是,Django 给了我以下错误:
AttributeError at /app/home/
'SessionStore' object has no attribute 'user'
Run Code Online (Sandbox Code Playgroud)
是的,我不知道我在做什么。