1 Auth模块是什么

Auth模块是Django自带的用户认证模块:

我们在开发一个网站的时候,无可避免的需要设计实现网站的用户系统。此时我们需要实现包括用户注册、用户登录、用户认证、注销、修改密码等功能,这还真是个麻烦的事情呢。

Django作为一个完美主义者的终极框架,当然也会想到用户的这些痛点。它内置了强大的用户认证系统--auth,它默认使用 auth_user 表来存储用户数据。

2 auth模块常用方法

from django.contrib import auth

authenticate()

提供了用户认证功能,即验证用户名以及密码是否正确,一般需要username 、password两个关键字参数。

如果认证成功(用户名和密码正确有效),便会返回一个 User 对象。

authenticate()会在该 User 对象上设置一个属性来标识后端已经认证了该用户,且该信息在后续的登录过程中是需要的。

用法:

user = authenticate(username='usernamer',password='password')

login(HttpRequest, user)

该函数接受一个HttpRequest对象,以及一个经过认证的User对象。

该函数实现一个用户登录的功能。它本质上会在后端为该用户生成相关session数据。

用法:

from django.contrib.auth import authenticate, login

def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
# Redirect to a success page.
...
else:
# Return an 'invalid login' error message.
...

logout(request)

该函数接受一个HttpRequest对象,无返回值。

当调用该函数时,当前请求的session信息会全部清除。该用户即使没有登录,使用该函数也不会报错。

用法:

from django.contrib.auth import logout

def logout_view(request):
logout(request)
# Redirect to a success page.

is_authenticated()

用来判断当前请求是否通过了认证。

用法:

def my_view(request):
if not request.user.is_authenticated():
return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))

login_requierd()

auth 给我们提供的一个装饰器工具,用来快捷的给某个视图添加登录校验。

用法:

from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
...

若用户没有登录,则会跳转到django默认的 登录URL '/accounts/login/ ' 并传递当前访问url的绝对路径 (登陆成功后,会重定向到该路径)。

如果需要自定义登录的URL,则需要在settings.py文件中通过LOGIN_URL进行修改。

示例:

LOGIN_URL = '/login/'  # 这里配置成你项目登录页面的路由

create_user()

auth 提供的一个创建新用户的方法,需要提供必要参数(username、password)等。

用法:

from django.contrib.auth.models import User
user = User.objects.create_user(username='用户名',password='密码',email='邮箱',...)

create_superuser()

auth 提供的一个创建新的超级用户的方法,需要提供必要参数(username、password)等。

用法:

from django.contrib.auth.models import User
user = User.objects.create_superuser(username='用户名',password='密码',email='邮箱',...)

check_password(password)

auth 提供的一个检查密码是否正确的方法,需要提供当前请求用户的密码。

密码正确返回True,否则返回False。

用法:

ok = user.check_password('密码')

set_password(password)

auth 提供的一个修改密码的方法,接收 要设置的新密码 作为参数。

注意:设置完一定要调用用户对象的save方法!!!

用法:

user.set_password(password='')
user.save()
@login_required
def set_password(request):
user = request.user
err_msg = ''
if request.method == 'POST':
old_password = request.POST.get('old_password', '')
new_password = request.POST.get('new_password', '')
repeat_password = request.POST.get('repeat_password', '')
# 检查旧密码是否正确
if user.check_password(old_password):
if not new_password:
err_msg = '新密码不能为空'
elif new_password != repeat_password:
err_msg = '两次密码不一致'
else:
user.set_password(new_password)
user.save()
return redirect("/login/")
else:
err_msg = '原密码输入错误'
content = {
'err_msg': err_msg,
}
return render(request, 'set_password.html', content)

一个修改密码的简单示例

User对象的属性

User对象属性:username, password

is_staff : 用户是否拥有网站的管理权限.

is_active : 是否允许用户登录, 设置为 False,可以在不删除用户的前提下禁止用户登录。

3 扩展默认的auth_user表

这内置的认证系统这么好用,但是auth_user表字段都是固定的那几个,我在项目中没法拿来直接使用啊!

比如,我想要加一个存储用户手机号的字段,怎么办?

聪明的你可能会想到新建另外一张表然后通过一对一和内置的auth_user表关联,这样虽然能满足要求但是有没有更好的实现方式呢?

答案是当然有了。

我们可以通过继承内置的 AbstractUser 类,来定义一个自己的Model类。

这样既能根据项目需求灵活的设计用户表,又能使用Django强大的认证系统了。

from django.contrib.auth.models import AbstractUser
class UserInfo(AbstractUser):
"""
用户信息表
"""
nid = models.AutoField(primary_key=True)
phone = models.CharField(max_length=11, null=True, unique=True) def __str__(self):
return self.username

注意:

按上面的方式扩展了内置的auth_user表之后,一定要在settings.py中告诉Django,我现在使用我新定义的UserInfo表来做用户认证。写法如下:

# 引用Django自带的User表,继承使用时需要设置
AUTH_USER_MODEL = "app名.UserInfo"

再次注意:

一旦我们指定了新的认证系统所使用的表,我们就需要重新在数据库中创建该表,而不能继续使用原来默认的auth_user表了。

可插拔式设计

import settings
import importlib def send_all(content):
for module_path in settings.NOTIFY_LIST:
module, class_name = module_path.rsplit('.',maxsplit=1)
# module = 'notify.email' class_name = 'Email'
mod = importlib.import_module(module) # mod就是模块名
# from notify import email
cls = getattr(mod,class_name) # 利用反射 获取到模块中类的变量名
obj = cls()
obj.send(content)
#__init__
NOTIFY_LIST = [
'notify.email.Email',
# 'notify.msg.Msg',
'notify.wechat.WeChat',
'notify.qq.QQ',
]
#setting
import notify

notify.send_all('今天鸡哥争取提前下课~')

#run
class WeChat(object):
def __init__(self):
pass # 发微信需要的前提准备工作 def send(self, content):
print('微信通知:%s' % content)
#WeChat

django进阶版4的更多相关文章

  1. django进阶版3

    hello... cookie与session 为什么会有cookie和session? 由于http协议是无状态的 无法记住用户是谁 cookie cookie是保存在客户端浏览器上的键值对 是服务 ...

  2. django进阶版2

    目录 批量插入数据 自定义分页器 创建多表关系的3种方法 全自动 全手动 半自动 form组件 如何渲染页面 第一种方式 第二种方式 第三种方式 如何显示错误信息 forms组件钩子函数 局部钩子 全 ...

  3. django进阶版1

    目录 字段中choice参数 MTV与MVC模型 AJAX(*********) Ajax普通请求 Ajax传json格式化数据 Ajax传文件 序列化组件 Ajax+sweetalert 字段中ch ...

  4. python学习-- django 2.1.7 ajax 请求 进阶版

    #原来版本 $.get("/add/",{'a':a,'b':b}, function(ret){ $('#result').html(ret)}) #进阶版  $.get(&qu ...

  5. zip伪加密文件分析(进阶版)

    作者近日偶然获得一misc题,本来以为手到擒来,毕竟这是个大家都讨论烂了的题,详情访问链接http://blog.csdn.net/ETF6996/article/details/51946250.既 ...

  6. Python之路,Day16 - Django 进阶

    Python之路,Day16 - Django 进阶   本节内容 自定义template tags 中间件 CRSF 权限管理 分页 Django分页 https://docs.djangoproj ...

  7. django进阶补充

    前言: 这篇博客对上篇博客django进阶作下补充. 一.效果图 前端界面较简单(丑),有两个功能: 从数据库中取出书名 eg: 新书A 在form表单输入书名,选择出版社,选择作者(多选),输入完毕 ...

  8. django进阶-3

    先看效果图: 登陆admin后的界面: 查看作者: 当然你也可以定制admin, 使界面更牛逼 数据库表结构: app01/models.py from django.db import models ...

  9. django进阶-4

    前言: 下篇博客写关于bootstrap... 一.如何在脚本测试django from django.db import models class Blog(models.Model): name ...

随机推荐

  1. 2016 NEERC, Moscow Subregional Contest K. Knights of the Old Republic(Kruskal思想)

    2016 NEERC, Moscow Subregional Contest K. Knights of the Old Republic 题意:有一张图,第i个点被占领需要ai个兵,而每个兵传送至该 ...

  2. Python学习日记(一)——初识Python

    Python的优势 互联网公司广泛使用python来做的事一般有:自动化运维.自动化测试.大数据分析.爬虫.Web等. Python与其他语言 C和Python.Java.C#: C  语言:代码编译 ...

  3. ACM之路(13)—— 树型dp

    最近刷了一套(5题)的树型dp题目:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=116767#overview,算是入了个门,做下总结. ...

  4. 安装完Pycharm,启动时碰到"failed to load jvm dll"的解决方案

    今天安装完系统,配置pycharm的环境的时候,启动pycharm时,碰到"failed to load jvm dll"的错误, 下面给出其解决方案: 安装Microsoft V ...

  5. 子类中执行父类的方法(引出super()与mro列表)

    1. 我们先想一下在python中如果子类方法中想执行父类的方法,有什么方式?大概有三种: Parent.__init__(self, name) # 通过父类的名字,指定调用父类的方法 super( ...

  6. Java如何接收前端传来的多层嵌套的复杂json串

    想看问题直接解决方式,直接拉到博文底部. Spring的controller在接收前端传参的时候如果参数使用@RequestBody标注的时候 @RequestBody 则会把前端参数转为JSON的形 ...

  7. 处理flutter http请求添加application/json报错Cannot set the body fields of a Request with content-type “application/json”

    在flutter中在http请求发送时设置"content-type": "application/json"会出现报错Cannot set the body ...

  8. postgresql获取表最后更新时间(通过触发器将时间写入另外一张表)

    通过触发器方式获取表最后更新时间,并将时间信息写入到另外一张表 一.创建测试表和表记录更新时间表 CREATE TABLE weather( city varchar(80), temp_lo int ...

  9. HearthBuddy 日志模块

    // Triton.Common.LogUtilities.CustomLogger // Token: 0x04000BD8 RID: 3032 private Level level_0 = Le ...

  10. leetcode-hard-ListNode-Copy List with Random Pointer-NO

    mycode 报错:Node with val 1 was not copied but a reference to the original one. 其实我并没有弄懂对于ListNode而言咋样 ...