【Django】Django用户认证: 利用Django Auth模块实现用户注册、登录与登出
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.http import HttpResponse
# 用户登录视图
def user_login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return HttpResponse("登录成功")
else:
return HttpResponse("用户名或密码错误")
else:
return HttpResponse("仅接受POST请求")
# 用户注册视图
def register_user(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = User.objects.create_user(username=username, password=password)
return HttpResponse("注册成功")
else:
return HttpResponse("仅接受POST请求")
# 用户登出视图
def user_logout(request):
logout(request)
return HttpResponse("登出成功")
这段代码提供了用户登录、注册以及登出的简单视图函数示例。在实际应用中,你需要将这些视图函数与URL配置对应起来,并且在实际环境中应该加入更多的安全措施,比如密码散列、CSRF保护等。
评论已关闭