一 分析源码 User |
Django的标准库存放在 django.contrib 包中。每个子包都是一个独立的附加功能包。
这些子包一般是互相独立的,不过有些django.contrib子包需要依赖其他子包,其中django.contrib.auth 为Django的用户验证框架
1. 导入方法
from django.contrib.auth.models import User
2. 分析User继承链
User --> AbstractUser --> (AbstractBaseUser, PermissionsMixin)
UserManger --> BaseUserManager
其中类AbstractUser内部中 username、first_name、last_name、email、is_staff、is_active、objects = UserManager()
类UserManager内部中 create_user()和create_superuser()
类AbstractBaseUser内部中 password、last_login、is_authenticated、set_password()
3. 小结
模仿 AbstractUser继承 AbstractBaseUser,调用UserManager(),实现账号定制
二 账号定制 |
# 用来创建用户 class MyUserManager(BaseUserManager): def create_user(self, email, name, password=None): if not email: raise ValueError(‘Users must have an email address‘) user = self.model( email=self.normalize_email(email), name=name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name, password): user = self.create_user( email, password=password, name=name, ) user.is_admin = True user.save(using=self._db) return user # 定制账号基本信息 class Account(AbstractBaseUser): email = models.EmailField( verbose_name=‘email address‘, max_length=255, unique=True, ) name = models.CharField(max_length=32) role = models.ForeignKey("Role", blank=True, null=True) customer = models.OneToOneField("Customer", blank=True, null=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = ‘email‘ REQUIRED_FIELDS = [‘name‘] # 其他基本信息......
参考链接 https://docs.djangoproject.com/en/1.11/topics/auth/customizing/
三 登录与退出 |
1. 导入方法
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
2. 分析模块
@login_required 验证需要登录的页面,否则跳转找配置里的登录页面 LOGIN_URL = ‘/login/‘
authenticate(username=username, password=password),认证通过返回user对象,否则None
login(request, user) 写入登录sessioin
logout(request) 清除登录session
3.3 示例
from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate, login, logout @login_required def dashboard(request): return render(request, ‘dashboard.html‘) def account_login(request): if request.method == "POST": username = request.POST.get(‘username‘) password = request.POST.get(‘password‘) user = authenticate(username=username, password=password) if user: login(request, user) return redirect(request.GET.get(‘next‘) or ‘/dashboard/‘) return render(request, ‘login.html‘) def account_logout(request): logout(request) return redirect(‘/login/‘)