自定义一个用户认证
详细参考官方文档:
https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#django.contrib.auth.models.PermissionsMixin.has_perms
一、创建用户的表
UserProfile():存放用户信息的表
UserProfileManager(): 用户创建用户的类方法
1、生成一个单独的Moel文件专门用来存放用户表
#!/usr/bin/env python # _*_coding:utf-8_*_ from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class UserProfileManager(BaseUserManager): def create_user(self, email, name, password=None): """ Creates and saves a User with the given email, date of birth and password. """ 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): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user(email, password=password, name=name ) user.is_admin = True user.save(using=self._db) return user class UserProfile(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) name = models.CharField(max_length=64) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) class Meta: verbose_name = '用户表' verbose_name_plural = '账户表' objects = UserProfileManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def get_full_name(self): # The user is identified by their email address return self.email def get_short_name(self): # The user is identified by their email address return self.email def __str__(self): # __unicode__ on Python 2 return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return self.is_admin