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 ...
随机推荐
- Ubuntu 修改 hosts 文件
sudo vi /etc/hosts sudo /etc/init.d/networking restart
- 设置linux中Tab键的宽度(可永久设置)
一.仅设置当前用户的Tab键宽度输入命令:vim ~/.vimrc然后:set tabstop=6 //将Tab键的宽度设置为6保存:ctrl+z+z(或:wq!)OK!二.设置所有用户的Tab键 ...
- 天大福利!世界第一科技出版公司 Springer 免费开放 400 多本电子书!
前几天,世界著名的科技期刊/图书出版公司施普林格(Springer)宣布:免费向公众开放 400 多本正版的电子书!! Springer 即施普林格出版社,于1842 年在德国柏林创立,20 世纪60 ...
- Vue Cli 3 报错:router is not defined
报错内容: 报错原因: 代码全部放在了路由配置的main.js文件里,router没有定义,使用的时候报undefined 解决方法: 把router.beforeEach放在main.js里面
- dijkstra preiority_queue优化 紫书学习
#include<bits/stdc++.h> using namespace std; const int maxn=1000+10; const int INF=1000000000; ...
- 数据库SQL语言从入门到精通--Part 5--E-R图(实体联系图)用来描述数据库图例
数据库从入门到精通合集(超详细,学习数据库必看) E-R图也称实体-联系图(Entity Relationship Diagram),提供了表示实体类型.属性和联系的方法,用来描述现实世界的概念模型. ...
- Eugene and an array(边界麻烦的模拟)
一道看似小学生的题,搞了我几个小时...... 首先思路就有两种: \(Ⅰ.找和为0的bad子串,再用n*(n+1)/2-bad子串得到答案\) \(Ⅱ.找和不为0的good子串\) 如果你选择找ba ...
- POJ2686(状压)
描述: \(m个城市有p条双向道路.道路的花费是道路的距离/票上的数字.给出n张票,求a->b的最短路\). 开始本来想老套路把城市状态来压缩,但城市最多可以有30个,故考虑把船票压缩. 定义\ ...
- Spring Cloud 学习 之 Spring Cloud Eureka(搭建)
Spring Boot版本:2.1.4.RELEASE Spring Cloud版本:Greenwich.SR1 文章目录 搭建服务注册中心: 注册服务提供者: 高可用注册中心: 搭建服务注册中心: ...
- 【T-SQL】基础——表别名
Som有时候我们需要为表设置别名,这样就可以方便的修改表. 如果在SSMS中,可以点击 Query-> SQL CMD mode --Set Alisa for the table:setvar ...