Django中的用户认证 (使用Django认证系统)
-
Django带有一个用户认证系统。 它处理用户账号、组、权限以及基于cookie的用户会话。
-
作用:
- 添加普通用户和超级用户
- 修改密码
-
文档参见
-
User模型类
-
位置:
from django.contrib.auth.models import User
-
默认user的基本属性有:
属性名 类型 是否必选 username 用户名 是 password 密码 是 email 邮箱 可选 first_name 名 last_name 姓 is_superuser 是否是管理员帐号(/admin) is_staff 是否可以访问admin管理界面 is_active 是否是活跃用户,默认True。一般不删除用户,而是将用户的is_active设为False。 last_login 上一次的登录时间 date_joined 用户创建的时间
auth基本模型操作:
-
创建用户
-
创建普通用户create_user
from django.contrib.auth.models import User user = User.objects.create_user(username='用户名', password='密码', email='邮箱',...)
-
创建超级用户create_superuser
from django.contrib.auth.models import User user = User.objects.create_superuser(username='用户名', password='密码', email='邮箱',...)
-
-
删除用户
from django.contrib.auth.models import User try: user = User.objects.get(username='用户名') user.is_active = False # 记当前用户无效 user.save() print("删除普通用户成功!") except: print("删除普通用户失败")
-
修改密码set_password
from django.contrib.auth.models import User try: user = User.objects.get(username='xiaonao') user.set_password('654321') user.save() return HttpResponse("修改密码成功!") except: return HttpResponse("修改密码失败!")
-
检查密码是否正确check_password
from django.contrib.auth.models import User try: user = User.objects.get(username='xiaonao') if user.check_password('654321'): # 成功返回True,失败返回False return HttpResponse("密码正确") else: return HttpResponse("密码错误") except: return HttpResponse("没有此用户!")
auth扩展字段
如果需要在默认auth表上扩展新的字段,如phone
1,添加新的应用
2,定义模型类 继承 AbstractUser
3,settings.py中 指明 AUTH_USER_MODEL = '应用名.类名'
#models.py案例
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class UserInfo(AbstractUser):
phone = models.CharField(max_length=11, default='')
#settings.py添加配置
AUTH_USER_MODEL = 'user.UserInfo'
#添加用户
from user.models import UserInfo
UserInfo.objects.create_user(username='guoxiao', password='123456', phone='13488871101')