Django之Auth认证模块
Django的Auth模块提供了用户认证系统,它处理用户账号、组、权限以及基于cookie的用户会话。以下是使用Django Auth的一些基本示例:
- 用户注册:
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
def register_view(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = User.objects.create_user(username=username, password=password)
user.save()
# 登录新注册的用户
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return HttpResponse("注册并登录成功")
return HttpResponse("注册失败")
- 用户登录:
from django.contrib.auth import authenticate, login
from django.http import HttpResponse
def login_view(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("用户名或密码错误")
return HttpResponse("登录失败")
- 用户登出:
from django.contrib.auth import logout
from django.http import HttpResponse
def logout_view(request):
logout(request)
return HttpResponse("登出成功")
- 检查用户是否登录:
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
# 这里的代码只有当用户登录后才会执行
...
这些示例展示了如何使用Django Auth进行用户注册、登录、登出以及如何确保视图只对登录用户开放。
评论已关闭