Django学习笔记-默认的用户认证系统(auth)
from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from django.contrib import auth, messages
def register(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = User.objects.create_user(username=username, password=password)
return redirect('index')
return render(request, 'register.html')
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(request, username=username, password=password)
if user is not None:
auth.login(request, user)
return redirect('index')
else:
messages.error(request, 'Credentials not valid!')
return render(request, 'login.html')
def logout(request):
auth.logout(request)
return redirect('index')
这段代码提供了注册、登录和登出的视图函数示例,使用了Django的默认用户认证系统。注册函数创建了一个新用户,登录函数尝试验证用户凭据,如果成功则登录用户,登出函数注销当前用户。
评论已关闭