Django 内置的用户类AbstractUser与内置认证校验系统 学习笔记

这几天学习Django REST framework 时又用上了其内置的AbstractUser,正好复习整理一下,部分资源来自网络查找

内置的用户类AbstractUser

AbstractUser就是Django内置的一个 关于用户操作的类 ,它极大地方便了我们对model模型中对User用户类的设计。它的本质也就是一个封装好的父类,在设计用户模型的时候,继承它可以方便我们很多。

引入代码

models.py

#导入AbstractUser类
from django.contrib.auth.models import AbstractUser

#直接继承就可以了,如果有需要就向寻常model一样写字段就可以
class User(AbstractUser):
    pass

AbstractUser的源码 查看他的内置字段

class AbstractUser(AbstractBaseUser, PermissionsMixin):
    """
    An abstract base class implementing a fully featured User model with
    admin-compliant permissions.

    Username and password are required. Other fields are optional.
    """
    username_validator = UnicodeUsernameValidator()

    username = models.CharField(
        _('username'),
        max_length=150,
        unique=True,
        help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
        validators=[username_validator],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=150, blank=True)
    email = models.EmailField(_('email address'), blank=True)
    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_('Designates whether the user can log into this admin site.'),
    )
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'
        ),
    )
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    objects = UserManager()

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')
        abstract = True

    def clean(self):
        super().clean()
        self.email = self.__class__.objects.normalize_email(self.email)

    def get_full_name(self):
        """
        Return the first_name plus the last_name, with a space in between.
        """
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        """Return the short name for the user."""
        return self.first_name

    def email_user(self, subject, message, from_email=None, **kwargs):
        """Send an email to this user."""
        send_mail(subject, message, from_email, [self.email], **kwargs)

源码

内置认证校验系统

Django自带的用户认证校主要就是认证用户名密码的正确与否

要使用它,首先需要在settings文件里面配置

settings.py

#使用内置的认证校验系统
AUTH_USER_MODEL = "user.User"

配合自带的用户类AbstractUser一起使用的
通常使用在类视图中的post方法校验用户登录等操作
在view中的具体代码如下

views.py

class LoginView(View):

    def get(self,request):
        #逻辑代码
        return render(request,'login.html')

    def post(self,request):
        # 获取前端传递过来的用户名和密码
        username = request.POST.get('username')
        pwd = request.POST.get('pwd')
        record = request.POST.get('record')
        # 进行数据校验
        if not all([username,pwd]):
            return HttpResponse('数据输入不完整')
        # 验证用户名和密码是否正确
        #其中的username和pwd就是拿到的用户前端输入的信息
        user = authenticate(username=username,password=pwd)
        return render(request,''index.html')