models.py

 from django.db import models

 from django.contrib.auth.models import AbstractUser

 class Userinfo(AbstractUser):

     email = models.EmailField()

models.py

seetings.py

AUTH_USER_MODEL='app01.Userinfo'#自定义认证表:应用名.类名

views.py

 from django.shortcuts import render, HttpResponse, redirect
from django import forms
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
import re
from app01 import models
from django.http import JsonResponse
from django.urls import reverse
from django.contrib import auth # Create your views here. def name_valid(value):
name_re = re.compile(r'^[\d]+')
ret = name_re.match(value)
if ret:
raise ValidationError('用户名不能以数字开头!') class RegisterForm(forms.Form):
name = forms.CharField(
required=True,
label='用户名:',
min_length=6,
max_length=32,
help_text='只能有字母数字下划线组成,且不能以数字开头,长度6到32位!',
# initial='admin123_',
error_messages={
'required': '用户名不能为空!',
'min_length': '长度不能少于6位!',
'max_length': '长度不能超过32位!',
},
validators=[RegexValidator(r'^[a-zA-Z0-9_]+$', '用户名只能包含字母数字下划线!'), name_valid],
)
password = forms.CharField(
required=True,
label='密码:',
min_length=6,
max_length=32,
help_text='长度6到32位!',
initial='',
error_messages={
'required': '密码不能为空!',
'min_length': '长度不能少于6位!',
'max_length': '长度不能超过32位!',
},
widget=forms.PasswordInput(render_value=True),
)
r_password = forms.CharField(
required=True,
label='确认密码:',
min_length=6,
max_length=32,
help_text='长度6到32位!',
initial='',
error_messages={
'required': '密码不能为空!',
'min_length': '长度不能少于6位!',
'max_length': '长度不能超过32位!',
},
widget=forms.PasswordInput(render_value=True),
)
email = forms.EmailField(
required=True,
label='邮箱',
error_messages={
'required': '邮箱不能为空!',
}
) def __init__(self, *args, **kwargs):
super(RegisterForm, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs.update({'class': 'form-control'}) def clean_name(self):
pass
return self.cleaned_data.get('name') def clean_password(self):
pass
return self.cleaned_data.get('password') def clean_r_password(self):
pass
return self.cleaned_data.get('r_password') def clean_email(self):
pass
return self.cleaned_data.get('email') def clean(self):
password = self.cleaned_data.get('password')
r_password = self.cleaned_data.get('r_password')
if password != r_password:
self.add_error('r_password', '两次密码不一致!')
raise ValidationError('两次密码不一致!')
else:
return self.cleaned_data # 注册
def register(request):
if request.method == 'GET':
register_obj = RegisterForm()
return render(request, 'register.html', {'register_obj': register_obj})
elif request.method == 'POST':
data = request.POST
# print(data)
register_obj = RegisterForm(data)
if register_obj.is_valid():
user_obj = register_obj.cleaned_data
print(user_obj)
username = user_obj.get('name')
password = user_obj.get('password')
email = user_obj.get('email') if not models.Userinfo.objects.filter(username=username).exists():
new_obj = models.Userinfo.objects.create_user(username=username, password=password, email=email)
print(f'新用户{username}注册成功!')
return redirect('login')
else:
register_obj.add_error('name', '用户名已存在!')
return render(request, 'register.html', {'register_obj': register_obj})
else:
return render(request, 'register.html', {'register_obj': register_obj})
# 登录
def login(request):
if request.method == 'GET':
return render(request, 'login.html')
elif request.method == 'POST':
# print(request.POST)
username = request.POST.get('username')
password = request.POST.get('password') user_obj = auth.authenticate(username=username, password=password)
print(user_obj)
if user_obj:
auth.login(request, user_obj)
return JsonResponse({'status': 1, 'url': reverse('index')})
else:
return JsonResponse({'status': 0, 'url': ''}) #访问认证
def index(request):
if request.user.is_authenticated:
print(request.user)
if request.method == 'GET':
return render(request, 'index.html')
else:
return redirect('login') #注销
def logout(request):
auth.logout(request)
return redirect('login') #修改密码
def reset_psd(request):
if request.user.is_authenticated:
if request.method == 'GET':
return render(request, 'reset_psd.html')
elif request.method == 'POST':
old_password = request.POST.get('old_password')
new_password = request.POST.get('new_password')
r_new_password = request.POST.get('r_new_password')
# ret=request.user.check_password(old_password)
# print(ret)
if request.user.check_password(old_password):
if new_password == r_new_password:
request.user.set_password(new_password)
request.user.save()
return JsonResponse({'status': True, 'info': '操作成功!', 'url': reverse('index')})
else:
return JsonResponse({'status': False, 'info': '两次新密码不一致!', 'url': ''})
else:
return JsonResponse({'status': False, 'info': '操作失败:原密码输入有误!', 'url': ''})
return JsonResponse({'status': False, 'info': '操作失败!', 'url': ''}) else:
return redirect('login')

views.py

urls.py

 from django.conf.urls import url
from django.contrib import admin
from app01 import views urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^register/', views.register, name='register'),
url(r'^login/', views.login, name='login'),
url(r'^index/', views.index, name='index'),
url(r'^logout/', views.logout, name='logout'),
url(r'^reset_psd/', views.reset_psd, name='reset_psd'), ]

urls.py

templates

register.html

 {% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">
<title>用户注册</title>
</head>
<body style="background-image: url('{% static 'images/register_bg.gif' %}');background-size: cover">
<div class="container">
<div class="row">
<div class="col-xs-6 col-xs-offset-3" style="margin-top: 12%;">
<div class="container-fluid" style="background-color: rgba(255,255,255,0.2);border-radius: 5%">
<div class="row">
<h2 class="text-left col-xs-8 text-primary">新用户注册:</h2>
</div>
<div class="row" >
<form action="{% url 'register' %}" method="post" novalidate class="form-horizontal">
{% csrf_token %}
{% for field in register_obj %}
<div class="form-group" >
<label for="{{ field.id_for_label }}"
class="col-xs-3 control-label" >{{ field.label }}</label>
<div class="col-xs-7">
{{ field }}
<div style="height: 10px;" class="text-danger">{{ field.errors.0 }}</div>
</div>
</div>
{% endfor %}
<div class="form-group">
<div class="col-sm-7 col-xs-offset-3">
<span class="col-xs-10 text-success text-center"
style="line-height: 200%">已有账号,请<a href="{% url 'login' %}">登录</a>!</span>
<input type="submit" class="btn btn-success btn-sm col-xs-2 pull-right">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
<script src="{% static 'jquery-3.4.1.js' %}"></script>
<script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script>
</html>

register.html

login.html

 {% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">
<title>用户登录</title>
</head>
<body style="background-image: url('{% static "images/login_bg.jpg" %}');background-size: cover">
<div>
<div class="container">
<div class="row">
<div class='col-xs-4 col-xs-offset-4'>
<div class="row" style="margin-top: 50%;background-color: rgba(255,255,255,0.2 );border-radius: 3%">
<div class="row c1">
<h2 class=" col-xs-6 text-primary" style="margin-bottom: 30px">用户登录</h2>
</div>
<div class="row">
<div class="form-group" style="height: 60px;">
<label for="username" class="col-xs-3 control-label text-right">用户名:</label>
<div class="col-xs-8">
<input type="text" class="form-control" id="username">
<div class="text-danger"></div>
</div>
</div>
<div class="form-group" style="height: 60px;">
<label for="password" class="col-xs-3 control-label text-right">密码:</label>
<div class="col-xs-8">
<input type="password" class="form-control" id="password">
<div class="text-danger"></div>
</div>
</div>
<div class="form-group" style="height: 60px;">
{% csrf_token %}
<div class="col-xs-8 col-xs-offset-3">
<a href="{% url 'register' %}">
<button class="btn btn-primary col-xs-offset-2" id="register">注册</button>
</a>
<button class="btn btn-success col-xs-offset-2" id="submit">登录</button>
<div class=" text-danger"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div> </div>
</div>
</body>
<script src="{% static 'jquery-3.4.1.js' %}"></script>
<script src="{% static 'jquery-cookie-1.4.1.js' %}"></script>
<script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script>
<script>
$(function () {
$('#username').blur(function () {
if(username !== ''){$('#username').next().text('');}
});
$('#password').blur(function () {
if(username !== ''){$('#password').next().text('');}
});
$('#username').focus(function () {
if(username !== ''){$('#submit').next().text('');}
});
$('#password').focus(function () {
if(username !== ''){$('#submit').next().text('');}
}); $('#submit').click(function () { var username = $('#username').val().trim();
var password = $('#password').val().trim(); if (username === '' || password === '') {
if (username === '') {
$('#username').next().text('用户名不能为空!');
}
;
if (password === '') {
$('#password').next().text('密码不能为空!')
}
; } else {
$.ajax({
url: '{% url 'login' %}',
type: 'POST',
headers: {'X-CSRFToken': $.cookie('csrftoken')},
data: {
'username': username,
'password': password, },
success: function (request) {
console.log(request);
if (request.status === 1) {
location.href = request.url;
} else {
$('#submit').next().text('账号或密码有误!');
}
} })
} })
})
</script>
</html>

login.html

index.html

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>index</h1>
<a href="{% url 'logout' %}"><h6>注销</h6></a>
<a href="{% url 'reset_psd' %}">修改密码</a>
</body>
</html>

index.html

reset_psd.html

 {% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">
<title>修改密码</title>
</head>
<body>
<div><h3>当前用户:{{ username }}</h3>
<p>请输入原密码:<input type="password" id="old_password"></p>
<P>请输入新密码:<input type="password" id="new_password"></P>
<p>请确认新密码:<input type="password" id="r_new_password"></p>
{% csrf_token %}
<p><button class="btn btn-success" id="submit">保存</button></p>
</form>
</div>
</body>
<script src="{% static 'jquery-3.4.1.js' %}"></script>
<script src="{% static 'jquery-cookie-1.4.1.js' %}"></script>
<script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script>
<script>
$(function () {
$('#submit').click(function () {
var old_password=$('#old_password').val().trim();
var new_password=$('#new_password').val().trim();
var r_new_password=$('#r_new_password').val().trim(); if(old_password===''||new_password==='' || r_new_password===''){
alert('不允许有空!');
return false
}; if(new_password!==r_new_password){
alert('两次输入的新密码不一致,请重新确认输入!');
return false
};
$.ajax({
url:'{% url "reset_psd" %}',
type:'post',
headers:{'X-CSRFToken':$.cookie('csrftoken')},
data:{
old_password:old_password,
new_password:new_password,
r_new_password:r_new_password,
},
success:function (response) {
if(response.status===true){
alert(response.info);
location.href=response.url;
}
else {
alert(response.info)
}
}
}
)
})
})
</script>
</html>

reset_psd.hml

Django认证系统之自定义认证表的更多相关文章

  1. DRF内置认证组件之自定义认证系统

    自定义token认证 我们知道,在django项目中不管路由以及对应的视图类是如何写的,都会走到 dispatch 方法,进行路由分发, 在阅读 APIView类中的dispatch 方法的源码中,有 ...

  2. Django自定义用户认证系统之自定义用户模型

    参考文档:http://python.usyiyi.cn/django/topics/auth/customizing.html Django 自带的认证系统足够应付大多数情况,但你或许不打算使用现成 ...

  3. Django之博客系统:自定义认证

    前面我们在登录的时候,是通过输入用户名和密码来进行认证 user=authenticate(username=cd['username'],password=cd['password']) 这个是通过 ...

  4. Django(62)自定义认证类

    前言 如果我们不用使用drf那套认证规则,我们想自定义认证类,那么我们首先要知道,drf本身是如何定义认证规则的,也就是要查看它的源码是如何写的 源码分析 源码的入口在APIView.py文件下的di ...

  5. .Net Core 认证系统之Cookie认证源码解析

    接着上文.Net Core 认证系统源码解析,Cookie认证算是常用的认证模式,但是目前主流都是前后端分离,有点鸡肋但是,不考虑移动端的站点或者纯管理后台网站可以使用这种认证方式.注意:基于浏览器且 ...

  6. 源码剖析Django REST framework的认证方式及自定义认证

    源码剖析Django REST framework的认证方式 在前面说过,请求到达REST framework的时候,会对request进行二次封装,在封装的过程中会对客户端发送过来的request封 ...

  7. Django的认证系统

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

  8. Django之自带的认证系统 auth模块

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

  9. Django组件之认证系统

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

随机推荐

  1. 2019-2020-1 20199329 第二周测试(环境:ubuntu64位)

    2019-2020-1 20199329 第二周测试(环境:ubuntu64位) 实验一 0.每个.c一个文件,每个.h一个文件,文件名中最好有自己的学号 1.用Vi输入图中代码,并用gcc编译通过 ...

  2. Scala的Higher-Kinded类型

    Scala的Higher-Kinded类型 Higher-Kinded从字面意思上看是更高级的分类,也就是更高一级的抽象.我们先看个例子. 如果我们要在scala中实现一个对Seq[Int]的sum方 ...

  3. 解决Idea配置文件不显示中文的问题

    1.首先我们的IDEA文件编码一般都修改为utf-8(setting-->file encodings--->Global Encoding 和 Project Encoding 都设置为 ...

  4. 【JAVA基础】02 Java基础语法

    一.内容 注释 关键字 标识符 常量.进制和进制转换 变量 数据类型和类型转换 运算符 语句 二.注释 注释概述 用于解释说明程序的文字 Java中注释分类格式 单行注释 格式://注释文字 多行注释 ...

  5. IT服务,共享经济的下一个风口?

    前两天,在上千名CIO参加.释放10亿采购需求的2017华南CIO大会暨信息技术交易会上,一款"一站式IT工程师共享平台"成为大会关注焦点--这就是神州数码旗下的神州邦邦. 其实最 ...

  6. 图像处理之OpenCV - 缩放/旋转/裁剪/加噪声/高斯模糊

    Github地址 @ 缩放 void cv::resize ( InputArray src, OutputArray dst, Size dsize, , , int interpolation = ...

  7. 数学--数论--HDU 2802 F(N) 公式推导或矩阵快速幂

    Giving the N, can you tell me the answer of F(N)? Input Each test case contains a single integer N(1 ...

  8. P4168 蒲公英

    神仙分块,把减写成加调了半小时.. 不过这题也启示我们其实有的分块题要把多个块的信息拿到一起维护 以前做的都是每个块的信息单独维护 写的分块题还不太多,同时维护一个块的左右边界好像有点冗余,不过这样代 ...

  9. python selenium(键盘事件 Keys 类)

    1.导入Keys类 from selenium.webdriver.common.keys import Keys Keys.BACK_SPACE  删除输入框内结尾的单个字符 Keys.SPACE  ...

  10. Effective C++学习记录

    Effective C++算是看完了,但是并没有完全理解,也做不到记住所有,在此记录下55个条款及条款末的"请记住". 让自己习惯C++ 条款01:视C++为一个语言联邦 ① C ...