def login(request): if request.method == 'GET': return render(request, 'login.html', context={ 'form': LoginForm(), }) else: form = LoginForm(data=request.POST, request=request) # 需要传的参数是data+request, 只传data是不够的! if form.is_valid(): # LoginForm继承了AuthenticationForm, 会自动完成认证 auth.login(request, form.get_user()) # 将用户登陆 redirect_to = request.GET.get(key='next', default=reverse('web:personal')) # 重定向到要访问的地址,没有的话重定向到首页 return HttpResponseRedirect(redirect_to) else: # 认证失败 return render(request, 'login.html', context={ 'form': form })
def login_view(request): global loggedin if loggedin is 'true': return redirect('web:login_index') else: if request.method == 'POST': form = LoginForm(data=request.POST) if form.is_valid(): user = form.get_user() loggedin = 'true' login(request, user) if 'next' in request.POST: return redirect(request.POST.get('next')) else: return redirect('web:login_index') else: form = LoginForm() return render(request, 'web/login.html', {'form': form})