Django认证系统之自定义认证表
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认证系统之自定义认证表的更多相关文章
- DRF内置认证组件之自定义认证系统
自定义token认证 我们知道,在django项目中不管路由以及对应的视图类是如何写的,都会走到 dispatch 方法,进行路由分发, 在阅读 APIView类中的dispatch 方法的源码中,有 ...
- Django自定义用户认证系统之自定义用户模型
参考文档:http://python.usyiyi.cn/django/topics/auth/customizing.html Django 自带的认证系统足够应付大多数情况,但你或许不打算使用现成 ...
- Django之博客系统:自定义认证
前面我们在登录的时候,是通过输入用户名和密码来进行认证 user=authenticate(username=cd['username'],password=cd['password']) 这个是通过 ...
- Django(62)自定义认证类
前言 如果我们不用使用drf那套认证规则,我们想自定义认证类,那么我们首先要知道,drf本身是如何定义认证规则的,也就是要查看它的源码是如何写的 源码分析 源码的入口在APIView.py文件下的di ...
- .Net Core 认证系统之Cookie认证源码解析
接着上文.Net Core 认证系统源码解析,Cookie认证算是常用的认证模式,但是目前主流都是前后端分离,有点鸡肋但是,不考虑移动端的站点或者纯管理后台网站可以使用这种认证方式.注意:基于浏览器且 ...
- 源码剖析Django REST framework的认证方式及自定义认证
源码剖析Django REST framework的认证方式 在前面说过,请求到达REST framework的时候,会对request进行二次封装,在封装的过程中会对客户端发送过来的request封 ...
- Django的认证系统
Django自带的用户认证 我们在开发一个网站的时候,无可避免的需要设计实现网站的用户系统.此时我们需要实现包括用户注册.用户登录.用户认证.注销.修改密码等功能,这还真是个麻烦的事情呢. Djang ...
- Django之自带的认证系统 auth模块
01-Django自带的用户认证 我们在开发一个网站的时候,无可避免的需要设计实现网站的用户系统.此时我们需要实现包括用户注册.用户登录.用户认证.注销.修改密码等功能,这还真是个麻烦的事情呢. Dj ...
- Django组件之认证系统
Django自带的用户认证 我们在开发一个网站的时候,无可避免的需要设计实现网站的用户系统.此时我们需要实现包括用户注册.用户登录.用户认证.注销.修改密码等功能,这还真是个麻烦的事情呢. Dja ...
随机推荐
- python学习10字典
'''''''''字典(Dict)是python语言的一个最大的特征1.定义:是可变的无序集合,以键值对为基本元素,可以存储各种数据类型2.表示:{} 列表:[] 元组 () 字符串 ‘’ “” ‘‘ ...
- [http 1.1] M-POST
http://www.brainbell.com/tutors/XML/XML_Book_B/Sending_Messages_Using_M_POST.htm You can restrict me ...
- nginx与keepalived实现高可用+Apache实现负载均衡
nginx与keepalived实现高可用 本实验使用了四台虚拟机 两台需要安装nginx及keepalived 两台安装Apache nginx可以源码安装也可以用yum安装nginx yum安装n ...
- 徐州H
#include<bits/stdc++.h> using namespace std; #define rep(i,a,b) for(int i=a;i<=b;++i) #defi ...
- Python中字符串输出带颜色
格式:\033[显示方式;前景色;背景色m 说明:前景色 背景色 颜色---------------------------------------30 ...
- 从实践出发:微服务布道师告诉你Spring Cloud与Boot他如何选择
背景 随着公司业务量的飞速发展,平台面临的挑战已经远远大于业务,需求量不断增加,技术人员数量增加,面临的复杂度也大大增加.在这个背景下,平台的技术架构也完成了从传统的单体应用到微服务化的演进. 系统架 ...
- 通过fiddler抓取IDEA的请求
2019独角兽企业重金招聘Python工程师标准>>> 因为fiddler默认是代理的8888端口,所以设置一下IDEA的请求使用本地的8888作为代理发出. 1."EDI ...
- RDP凭据离线脱取
内网渗透-获取本地RDP密码 获取RDP 连接记录: reg query "HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Clie ...
- PLAI那些事_07 FAE with Deferred Substitution
FAE-parse : 一成不变 FAE-Value : interp的最终转让值 ;;numV: value ;;closureV: param-FAE(或value,或function) pair ...
- 惠普服务器ipmi配置方法
个人感觉惠普ipmi搞的比戴尔的好 惠普的ipmi口在服务器上的端口名称叫ilo 1.开机按F8进入ilo. 注:按晚了,会进入磁盘阵列配置页面,开机画面显示出来ilo相关的信息之后就要按F8. 2. ...