定义
Django带有一个用户认证系统。能处理用户账号、组、权限以及基于cookie的用户会话。
用户可以直接使用Django自带的用户表
基本字段
模型类位置 from django.contrib.auth.models import User
username 用户名
password 密码
email 邮箱
first_name 名
last_name 姓
is_superuser 是否是管理员
is_staff 是否可以访问admin管理界面
is_active 是否活跃用户,默认True
last_login 上一次登录时间
date_joined 用户创建的时间
创建用户
创建普通用户 create_user
from django.contrib.auth.models import User
user=User.objects.create_user(username="用户名",password="密码",...)
>>> from django.contrib.auth.models import User
>>> u=User.objects.create_user(username="张三",password='123456')
创建超级用户create_superuser
from django.contrib.auth.models import User
user=User.objects.create_superuser(username="用户名",password="密码",...)
删除用户-也是建议做伪删除
>>> try:
... user=User.objects.get(username="zhangsan")
... user.is_active=False #标记当前用户无效
... user.save()
... print("user delete success")
... except:
... print("user delete failed")
...
user delete success
校验密码
from django.contrib.auth import authenticate
user = authenticate(username=username,password=password)
返回值: 如果用户名密码校验成功则返回对应的user对象,否则返回None
>>> from django.contrib.auth import authenticate
>>> user = authenticate(username="zhangsan",password="123456")
修改密码
>>> try:
... user = User.objects.get(username="lisi")
... user.set_password("1234567")
... user.save()
... print("密码修改成功")
... except:
... print("密码修改失败")
...
密码修改成功
登录状态保持
from django.contrib.auth import authenticate,login,logout
def login(request):
# 登录
if request.method=="GET":
return render(request,"login.html")
elif request.method=="POST":
username=request.POST["username"]
password=request.POST["password"]
user=authenticate(username=username,password=password)
if not user:
return HttpResponse("---用户名或密码错误---")
else:
login(request,user) # 保持会话状态
return HttpResponse("index")
登录状态校验
@login_required
def index(request):
# 该视图必须为当前用户登录才可以访问
# 当前登录用户可通过 request.user 获取
user=request.user
return HttpResponse("欢迎 %s 来到首页"%user.username)
登录取消状态
def logout(request):
logout(request)
return HttpResponse("已登出")
示例
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render
# Create your views here.
from django.contrib.auth.models import User
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required
def reg_view(request):
if request.method=="GET":
return render(request,"register.html")
elif request.method=="POST":
username=request.POST["username"]
password_2=request.POST["password_2"]
password_1=request.POST["password_1"]
if password_2 != password_1:
return HttpRequest("两次密码输入不一致")
#查询用户名是否已注册
user=User.objects.create(username=username,password=password_1)
return HttpResponse('login')
def login(request):
# 登录
if request.method=="GET":
return render(request,"login.html")
elif request.method=="POST":
username=request.POST["username"]
password=request.POST["password"]
user=authenticate(username=username,password=password)
if not user:
return HttpResponse("---用户名或密码错误---")
else:
login(request,user)
return HttpResponse("index")
def logout(request):
logout(request)
return HttpResponse("已登出")
@login_required
def index(request):
user=request.user
return HttpResponse("欢迎 %s 来到首页"%user.username)
settings配置login_url
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
# 未登录情况下的跳转地址
LOGIN_URL='/login'
添加路由
内建用户表
内建用户字段不够用怎么办。这个时候可以扩展字段,通常有2中方式实现:
- 方案一:通过建立新表,跟内建表做1对1
- 方案二:继承内建的抽象user模型类(最常用)
继承内建抽象类
步骤:
- 添加新的应用
- 定义模型类,继承AbstractUser
- settings.py 知名AUTH_USER_MODEL=“应用名.类名”
注意: 需要在第一次migrate之前进行
演示:
settings.py
AUTH_USER_MODEL="hello.UserInfo"
模板层
from django.contrib.auth.models import AbstractUser
# 会继承表中所有字段
class UserInfo(AbstractUser):
phone=models.CharField(max_length=11,default="")
python mange.py makemigrations
python mange.py migrate
mysql> desc hello_userinfo;
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| password | varchar(128) | NO | | NULL | |
| last_login | datetime(6) | YES | | NULL | |
| is_superuser | tinyint(1) | NO | | NULL | |
| username | varchar(150) | NO | UNI | NULL | |
| first_name | varchar(30) | NO | | NULL | |
| last_name | varchar(150) | NO | | NULL | |
| email | varchar(254) | NO | | NULL | |
| is_staff | tinyint(1) | NO | | NULL | |
| is_active | tinyint(1) | NO | | NULL | |
| date_joined | datetime(6) | NO | | NULL | |
| phone | varchar(11) | NO | | NULL | |
+--------------+--------------+------+-----+---------+----------------+
12 rows in set (0.00 sec)
添加用户
>>> from hello.models import UserInfo
>>>
>>> UserInfo.objects.create_user(username='hulk',password='123456',phone='123456')
<UserInfo: hulk>