当前位置:   article > 正文

Django笔记--Django的Auth组件(用户认证)_django 用户认证(auth)组件

django 用户认证(auth)组件

Django笔记–Django的Auth组件(用户认证)

这篇文章来记录我学习Django中的Auth组件。

Django提供了一个强大的用户认证系统–Auth组件,对于实现用户认证的登录功能会更加方便。

导入auth模块与其相应内容

from django.contrib import auth     #导入auth模块
from django.contrib.auth.models import User    #导入数据库(用户数据储存在auth_user中)
from django.contrib.auth.decorators import login_required   #导入装饰器login_required
  • 1
  • 2
  • 3

auth组件中方法以及描述:

auth中的方法描述
authenticate(request,username=*,password=*)登录验证(若输入的账号密码正确,则返回一个对象。否则返回None)
login(request,userobj)记录userobj对象用户的登录状态(登录)
logout(request)退出目前登录用户的登录状态(注销)
is_authenticated()判断目前用户是否通过登录认证
@login_required登录判断的装饰器(未登录则跳转到默认的URL“/accounts/login/”中,并会记录当前访问的url路径)(下面有补充!!!)
create_user(username = *, password = *)创建普通用户
create_superuser(username=*,password=*,email=*)创建超级用户
check_password(password)判断当前登录用户的面是否与输入值相同(相同返回True,否则返回False)
set_password(password)修改当前登录用户的密码

对@login_required装饰器的补充,在未登录的默认跳转URl路径为/accounts/login/。其路径可以在settings.py中添加以下设置来修改设定(修改成默认URL路径为/login/)。

LOGIN_URL = '/login/'
  • 1

用户数据库(auth_user)中用户属性的部分介绍:

  • is_superuser:是否为超级管理员,more power
  • is_staff:是否可以登录管理页面(admin),可以登录但没有权限
  • is_active:是否允许用户登录

下面实战利用Auth组件实战操作,结合上Form组件简单制作了一个带有登录,注册,注销,修改密码功能的系统。

(路由)urls.py

from django.contrib import admin
from django.urls import path
from firstapp import views

urlpatterns = [
    path('admin/', admin.site.urls),    #管理页面
    path('register/', views.register),  #注册
    path('login/',views.login),         #登录
    path('index/',views.index),         #大厅
    path('logout/', views.logout),      #注销
    path('changepassword/', views.changepassword),   #修改密码
]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

(校验)forms.py

from django import forms
from django.forms import widgets
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError


class RegForm(forms.Form):
    username = forms.CharField(
        label="用户名",
        min_length=2,
        max_length=6,
        error_messages={
            'min_length': '用户名的长度不能小于2',
            'max_length':'用户名的长度不能大于6',
            'required':'用户名不能为空',
        }
    )

    password = forms.CharField(
        label="密码",
        widget=forms.widgets.PasswordInput(),
        error_messages={
            'required': '密码不能为空',
        }
    )

    re_password = forms.CharField(
        label="确认密码",
        widget=forms.widgets.PasswordInput(),
        error_messages={
            'required': '密码不能为空',
        }
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields:
            self.fields[field].widget.attrs.update({'class': 'form-control'})

    def clean(self):
        pwd = self.cleaned_data.get('password')
        re_pwd = self.cleaned_data.get('re_password')
        if pwd == re_pwd:
            return self.cleaned_data
        self.add_error('re_password', '两次密码不一致')
        raise ValidationError('两次密码不一致')

class LogForm(forms.Form):
    username = forms.CharField(
        label="用户名",
        error_messages={
            'required':'用户名不能为空',
        }
    )

    password = forms.CharField(
        label="密码",
        widget=forms.widgets.PasswordInput(),
        error_messages={
            'required': '密码不能为空',
        }
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields:
            self.fields[field].widget.attrs.update({'class': 'form-control '})


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69

(视图)views.py

from django.shortcuts import render,HttpResponse,redirect
from firstapp.forms import RegForm,LogForm
from django.contrib import auth
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required

def register(request):   #注册函数
    form_obj = RegForm()
    if request.method == 'POST':
        form_obj = RegForm(request.POST)
        if form_obj.is_valid():
            username=request.POST.get('username')
            password =request.POST.get('password')
            User.objects.create_user(username = username, password = password)
            return redirect('/login/')
    return render(request, 'register.html', {'form_obj': form_obj})

def login(request):    #登录函数
    form_obj = LogForm()
    if request.method =="POST":
        form_obj = LogForm(request.POST)
        if form_obj.is_valid():
            username = request.POST.get('username')
            password = request.POST.get('password')
            obj = auth.authenticate(request,username=username,password=password)
            if obj:
                auth.login(request,obj)
                path = request.GET.get("next") or '/index/'
                return redirect(path)
            else:
                print('用户名与密码不匹配')
    return render(request,'login.html' , {'form_obj': form_obj})

@login_required
def index(request):    #大厅函数
    return render(request,'index.html')

@login_required
def logout(request):    #注销函数
    auth.logout(request)
    return redirect('/login/')

@login_required
def changepassword(request):     #修改密码函数
    if request.method == 'GET':
        return render(request,'changepassword.html')
    oldpassword = request.POST.get('oldpassword')
    newpassword = request.POST.get('newpassword')
    if request.user.check_password(oldpassword):
        request.user.set_password(newpassword)
        request.user.save()
        return redirect('/login/')
    return redirect('/changepassword/')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53

(登录页面)login.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>登录</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.css">

</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-sm-offset-5">
            <h3>小小城序员--登录界面</h3>
        </div>
    </div>
    >
</div>


<div class="container">
    <div class="row">
        <div class="col-sm-8 col-sm-offset-2" style="margin-top: 70px">
            <form class="form-horizontal" novalidate action="" method="post">
                {% csrf_token %}
                <div class="form-group {% if form_obj.username.errors %} has-error {% endif %} "><!--用户名-->
                    <label for="{{ form_obj.username.id_for_label }}"
                           class="col-sm-2 control-label">{{ form_obj.username.label }}</label>
                    <div class="col-sm-10">
                        {{ form_obj.username }}
                        <span id="helpBlock2" class="help-block">{{ form_obj.username.errors }}</span>
                    </div>
                </div>
                <div class="form-group {% if form_obj.password.errors %} has-error {% endif %} "><!--密码-->
                    <label for="{{ form_obj.password.id_for_label }}"
                           class="col-sm-2 control-label">{{ form_obj.password.label }}</label>
                    <div class="col-sm-10">
                        {{ form_obj.password }}
                        <span id="helpBlock2" class="help-block">{{ form_obj.password.errors }}</span>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-block btn-success">登录</button>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <a class="btn btn-block btn-warning" href="/register/" style="color: white;">注册</a>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="/static/Jquery-3.3.1.js"></script>
<script>
    $('input').focus(function () {
        $(this).next().text('').parent().parent().removeClass('has-error')
    })
</script>

</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66

(注册页面)register.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>注册</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.css">

</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-sm-offset-5">
            <h3>小小城序员--注册界面</h3>
        </div>
    </div>>
</div>

<div class="container">
    <div class="row">
        <div class="col-sm-8 col-sm-offset-2" style="margin-top: 70px">
            <form class="form-horizontal" novalidate action="" method="post">
                {% csrf_token %}
                <div class="form-group {% if form_obj.username.errors %} has-error {% endif %} "><!--用户名-->
                    <label for="{{ form_obj.username.id_for_label }}"
                           class="col-sm-2 control-label">{{ form_obj.username.label }}</label>
                    <div class="col-sm-10">
                        {{ form_obj.username }}
                        <span id="helpBlock2" class="help-block">{{ form_obj.username.errors }}</span>
                    </div>
                </div>
                <div class="form-group {% if form_obj.password.errors %} has-error {% endif %} "><!--密码-->
                    <label for="{{ form_obj.password.id_for_label }}"
                           class="col-sm-2 control-label">{{ form_obj.password.label }}</label>
                    <div class="col-sm-10">
                        {{ form_obj.password }}
                        <span id="helpBlock2" class="help-block">{{ form_obj.password.errors }}</span>
                    </div>
                </div>
                <div class="form-group {% if form_obj.re_password.errors %} has-error {% endif %}"><!--确认密码-->
                    <label for="{{ form_obj.re_password.id_for_label }}"
                           class="col-sm-2 control-label">{{ form_obj.re_password.label }}</label>
                    <div class="col-sm-10">
                        {{ form_obj.re_password }}
                        <span id="helpBlock2" class="help-block">{{ form_obj.re_password.errors }}</span>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-block btn-success">注册</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="/static/Jquery-3.3.1.js"></script>
<script>

    $('input').focus(function () {
        $(this).next().text('').parent().parent().removeClass('has-error')
    })
</script>

</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68

(大厅页面)index.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>大厅</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.css">
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-sm-offset-5">
            <h3>小小城序员--大厅界面</h3>
        </div>
        <div class="col-md-offset-6">
            <a  class="btn btn-danger" href="/logout/" style="color: white;">注销账号</a>
        </div>
        <br>
         <div class="col-md-offset-6">
            <a  class="btn btn-warning" href="/changepassword/" style="color: white;">修改密码</a>
        </div>
    </div>>
</div>

</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

(修改密码页面)changepassword.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>修改密码</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.css">

</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-sm-offset-5">
            <h3>小小城序员--修改密码界面</h3>
        </div>
    </div>>
</div>


<div class="container">
    <div class="row">
        <div class="col-sm-8 col-sm-offset-2" style="margin-top: 70px">
            <form class="form-horizontal" novalidate action="" method="post">
                {% csrf_token %}
                <div class="form-group  "><!--旧密码-->
                    <label class="col-sm-2 control-label">旧密码</label>
                    <div class="col-sm-10">
                        <input type="password" class="form-control" placeholder="请输入旧密码" name="oldpassword" >
                    </div>
                </div>
                <div class="form-group  "><!--新密码-->
                    <label class="col-sm-2 control-label">新密码</label>
                    <div class="col-sm-10">
                        <input type="password" class="form-control" placeholder="请输入新密码" name="newpassword" >
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-block btn-success">修改</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

成果图:(代码重点是实现Auth组件的使用,所以页面比较普通)
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述就记录到此,还在不断努力学习中!!!
END!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/71696
推荐阅读
相关标签
  

闽ICP备14008679号