Django实现自定义用户模块
Django中自带的User Model使用起来是比较方便的,但是一般跟我们系统的需求有些出入,或者少了一些必要的属性,或者多了些不必要的属性,这是就需要我们自己定义User Model,自定义用户模块。
虽然自定义了用户模块,但是不影响Django原有的用户认证体系。
1.
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser class ANUserManager(BaseUserManager): def create_user(self, username, password=None): """ Creates and saves a User with the given user name and password. """ if not username: raise ValueError(_('Users must have an username')) user = self.model( username=username, ) user.set_password(password) user.is_admin = False user.save(using=self._db) return user def create_superuser(self, username, password): """ Creates and saves a superuser with the given user name and password. """ user = self.create_user( password=password, username=username ) user.is_admin = True user.save(using=self._db) return user class Meta: verbose_name = _("System User") verbose_name_plural = _("System User")
2.
class SysUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=100, null=False, verbose_name=_('用户名'), help_text=_('用户名'), unique=True, db_index=True ) email = models.EmailField(max_length=254, verbose_name=_('邮件地址'), help_text=_('邮件地址'), null=True, unique=False, blank=True) phone = models.CharField(max_length=20, verbose_name=_('电话'), help_text=_('电话'), null=True, blank=True, unique=True) objects = ANUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] def has_perms(self, perm, obj=None): return True class Meta: verbose_name = _("用户") verbose_name_plural = _("用户")
3. 在settings.py中插入一句
AUTH_USER_MODEL = 'app.SysUser'