赞
踩
这篇文章来记录我学习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
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/'
用户数据库(auth_user)中用户属性的部分介绍:
下面实战利用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), #修改密码
]
(校验)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 '})
(视图)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/')
(登录页面)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>
(注册页面)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>
(大厅页面)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>
(修改密码页面)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>
成果图:(代码重点是实现Auth组件的使用,所以页面比较普通)
就记录到此,还在不断努力学习中!!!
END!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。