Django auth用户认证模块

Django auth用户认证模块

  • 1、Django auth用户认证
  • 2、Django auth用户模型
  • 3、自定义auth用户模型
  • 4、数据迁移
  • 5、web开发一个应用
    • 5.1 定义路由
      • 1.一级路由
      • 2.二级路由
    • 5.2 定义视图函数
    • 5.3 定义模板

1、Django auth用户认证

Django auth用户认证自带了一套用户认证模块:
from django.contrib import auth

2、Django auth用户模型

Django auth用户认证,必然少不了该模块的模型(models):
该模块的模型(models) :
1.AbstractBaseUser --> 他是一个基类

class AbstractBaseUser(models.Model):
    password = models.CharField(_("password"), max_length=128)
    last_login = models.DateTimeField(_("last login"), blank=True, null=True)
    is_active = True
    REQUIRED_FIELDS = []
    _password = None
    class Meta:
        abstract = True

2.AbstractUser --> 继承AbstractBaseUser 也是一个抽象类

class AbstractUser(AbstractBaseUser, PermissionsMixin):
    username_validator = UnicodeUsernameValidator()
    username = models.CharField(_("username"),max_length=150,....)
    first_name = models.CharField(_("first name"), max_length=150, 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,.....)
    is_active = models.BooleanField(_("active"),default=True,....)
    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

3.User–> 继承AbstractUser

class User(AbstractUser):
    class Meta(AbstractUser.Meta):
        swappable = "AUTH_USER_MODEL"

3、自定义auth用户模型

我们只要重定义User就可以了,但是必须继承AbstractUser 类
并且在配置文件中需要定义:AUTH_USER_MODEL = "users.UserDetail"
users:是app应用名
UserDetail:是定义的类名

# users应用中models.py重定义auth用户模型
from django.db import models
from django.contrib.auth.models import AbstractUser
class UserDetail(AbstractUser):
    age = models.DateField(null=True)
    desc = models.TextField(null=True)
    sex = models.CharField(max_length=4)
    school_status = models.CharField(max_length=4)
    grade = models.CharField(max_length=16)

4、数据迁移

自定义好模型,就是数据迁移
python manage.py makemigratation
python manage.py migrate

5、web开发一个应用

5.1 定义路由

1.一级路由

from django.contrib import admin
from django.urls import path
from django.urls import re_path
from django.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path('^user/', include("users.urls")),
    re_path('^user/', include("users.urls")),
    # re_path(r'^user/',include(('users.urls',"users"),namespace="user")) 
    # 通过{% url 'user' %}访问
]

2.二级路由

from django.urls import re_path
from . import views
urlpatterns = [
    re_path('login/$', views.login, name='login'),
    re_path('register/$', views.register, name='register'),
]

5.2 定义视图函数

from django.shortcuts import render
from django.http import HttpResponseForbidden, JsonResponse
from django.contrib.auth import authenticate
from users.models import UserDetail
from utils.serializer import UserDetailSerializer

def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        username = request.POST.get('username')
        password = request.POST.get('password')
        request_user = authenticate(request, username=username, password=password)
        if request_user is not None:
            return render(request, 'index.html', {'request_user': request_user})
        else:
            return render(request, 'login.html')

def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        data = {
            'username': request.POST.get('username'),
            'password': request.POST.get('password'),
            'age': request.POST.get('age'),
            'desc': request.POST.get('desc'),
            'sex': request.POST.get('sex'),
            'school_status': request.POST.get('school_status'),
            'grade': request.POST.get('grade'),
        }
        serializer = UserDetailSerializer(data=data)
        if serializer.is_valid():
        	# 如果要使用authenticate()函数认证用户,必须要对password进行哈希加密处理,而create_user()创建用户,就对密码进行了哈希,最好使用create_user创建用户
            request_user = UserDetail.objects.create_user(**serializer.data)
            return render(request, 'index.html', {'request_user': request_user})
        else:
            return HttpResponseForbidden("注册失败")

5.3 定义模板

1、模板调用关系:login继承base,并包含form
2、模板调用关系:register继承base,并包含form


DOCTYPE html>
{% load static %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}{% endblock title %}title>
    <link type="text/css" rel="stylesheet" href="{% static 'layui/css/layui.css' %}">
    <script src="{% static 'layui/layui.js' %}">script>
head>
<body>
<div class="layui-header" style="background-color: bisque; display: flex;align-items: center">
    <div class="layui-container">
        <div class="layui-row">
            {% if request_user %}
                <div class="layui-col-md2 layui-col-md-offset10">
                    <i class="layui-icon layui-icon-user layui-circle" style="font-size: 24px; color: #f92e27; background-color: #eeeeee">i>
                    <button type="button" class="layui-btn layui-btn-primary">
                        <a href="#">注销a>
                    button>
                div>
            {% else %}
                <div class="layui-col-md2 layui-col-md-offset10">
                    <div class="layui-btn-group">
                        <button type="button" class="layui-btn layui-btn-primary">
                            <a href="{% url 'user:login' %}">登录a>
                        button>
                        <button type="button" class="layui-btn layui-btn-primary">
                            <a href="{% url 'user:register' %}">注册a>
                        button>
                    div>
                div>
            {% endif %}
        div>
    div>
div>
<div class="layui-main">
    {% block content %}
    {% endblock content %}
div>
<div class="layui-footer" style="background-color: bisque; display: flex;align-items: center; height: 60px">
    {% block footer %}
    {% endblock footer %}
div>
body>
{% block scripts %}
{% endblock scripts %}
html>


<form class="layui-form layui-form-pane" action="{% url form_type %}" method="post">
    {% csrf_token %}
    <div class="layui-form-item">
        <label for="id_username" class="layui-form-label">用户名label>
        <div class="layui-input-block">
            <input class="layui-input" type="text" id="id_username" name="username" autocomplete="off"
                   lay-verify="required|tLength" required>
        div>
        {#        <div class="layui-form-mid layui-word-aux">{{ huit_name }}div>#}
    div>

    <div class="layui-form-item">
        <label for="id_password" class="layui-form-label">密码label>
        <div class="layui-input-block">
            <input class="layui-input" type="password" id="id_password" name="password" autocomplete="off"
                   lay-verify="required|tLength" required>
        div>
        {#        <div class="layui-form-mid layui-word-aux">{{ huit_pwd }}div>#}
    div>
    {% if form_type == 'user:login' %}
        <div class="layui-form-item">
            <label for="id_check_code" class="layui-form-label">验证码label>
            <div class="layui-input-block">
                <input class="layui-input" type="text" id="id_check_code" name="check_code">
                <img src="#" alt="验证码">
            div>
            {#            <div class="layui-form-mid layui-word-aux"><img src="#" alt="验证码">div>#}
        div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <input type="checkbox" id="id_un_auth" name="un_auth" title="30天免密登录" lay-skin="primary">
            div>
        div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交button>
                <button type="reset" class="layui-btn layui-btn-primary">重置button>
            div>
        div>
    {% endif %}
    {% if form_type == 'user:register' %}
        <div class="layui-form-item">
            <label for="id_auth_pwd" class="layui-form-label">确认密码label>
            <div class="layui-input-block">
                <input class="layui-input" type="text" id="id_auth_pwd" name="auth_pwd"
                       lay-verify="required|tLength" required>
                <span class="err_auth_pwd">span>
            div>
        div>
        <div class="layui-form-item">
            <label for="id_age" class="layui-form-label">生日日期label>
            <div class="layui-input-inline">
                <input class="layui-input" type="text" id="id_age" name="age" autocomplete="off">
                <span class="err_age">span>
            div>
        div>
        <div class="layui-form-item layui-form-text">
            <label for="id_desc" class="layui-form-label">性格描述label>
            <div class="layui-input-block">
                <textarea class="layui-textarea" type="text" id="id_desc" name="desc">textarea>
            div>
        div>
        <div class="layui-form-item" pane>
            <label for="id_sex" class="layui-form-label">性别label>
            <div class="layui-input-block">
                <input type="radio" id="id_sex" name="sex" checked title="">
                <input type="radio" id="id_sex" name="sex" title="">
            div>
        div>
        <div class="layui-form-item " pane>
            <label for="id_school_status" class="layui-form-label">是否在读label>
            <div class="layui-input-block">
                <input type="radio" id="id_school_status" name="school_status" checked title="">
                <input type="radio" id="id_school_status" name="school_status" title="">
            div>
        div>
        <div class="layui-form-item">
            <label for="id_grade" class="layui-form-label">年级label>
            <div class="layui-input-block">
                <select name="grade" lay-verify="required" id="id_grade">
                    <option value="1">一年级option>
                    <option value="2">二年级option>
                    <option value="3">三年级option>
                    <option value="4">四年级option>
                    <option value="5">五年级option>
                    <option value="6">六年级option>
                    <option value="7">七年级option>
                    <option value="8">八年级option>
                    <option value="9">九年级option>
                select>
            div>
        div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交button>
                <button type="reset" class="layui-btn layui-btn-primary">重置button>
            div>
        div>
    {% endif %}
form>


<script>
    //Demo
    layui.use(['form', 'laydate'], function () {
        let form = layui.form;
        let laydate = layui.laydate;
        form.verify({
            tLength: function (value) {
                let i = 0, sum = 0;
                for (i = 0; i < value.length; i++) {
                    //  console.log(value.charCodeAt(i));  获取字符的Unicode编码0~65535(2^16,两个字节)
                    if ((value.charCodeAt(i) >= 0) && (value.charCodeAt(i) <= 255))  // 判断字符是什么类型编码
                        sum = sum + 1;
                    else
                        sum = sum + 2;
                }
                if (sum < 4) {
                    return '最少输入4个字符或者2个中文字';
                } else if (sum > 16) {
                    return '最多输入32个字符或者16个中文字';
                }
            }
        });
        //提交
        form.on('submit(formDemo)', function (data) {
            layer.msg(JSON.stringify(data.field));
            return true;
        });
        laydate.render({
            elem: '#id_age', //指定元素
            type: 'date',
            {#format: 'yyyy-MM-dd'#}
        });
    });
script>


{% extends 'base.html' %}
{% load static %}
{% block title %}大圣传媒股份有限公司{% endblock title %}

{% block content %}
    {% include './pluges/form.html' with  form_type='user:login' %}
{% endblock content %}

{% block footer %}
    <div class="layui-footer footer footer-demo" style="background-color: bisque">
        <p><a href="#">Risk of Mediaa> © 2022 <a href="">大圣传媒a> Licensed 免责声明 开源协议 深ICP备2022002563号p>
    div>
{% endblock footer %}


{% extends 'base.html' %}
{% load static %}
{% block title %}大圣传媒股份有限公司{% endblock title %}

{% block content %}
     {% include './pluges/form.html' with form_type='user:register' %}
{% endblock content %}

{% block footer %}
    <div class="layui-footer footer footer-demo" style="background-color: bisque">
        <p><a href="#">Risk of Mediaa> © 2022 <a href="">大圣传媒a> Licensed 免责声明 开源协议 深ICP备2022002563号p>
    div>
{% endblock footer %}

你可能感兴趣的:(Django,django,python,后端)