from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
def login_view(request):
if request.method == 'POST':
username = request.POST.get('username') # 获取用户名
password = request.POST.get('password') # 获取密码
user = authenticate(username=username, password=password) # 验证用户
if user is not None:
login(request, user) # 登录用户
# 登录成功后的操作,如重定向到首页
return redirect('home')
else:
# 登录失败,返回错误信息
return render(request, 'login.html', {'error': '用户名或密码错误'})
else:
# 如果是 GET 请求,直接渲染登录页面
return render(request, 'login.html')