zoukankan      html  css  js  c++  java
  • Django认证系统之自定义认证表

    models.py

    1 from django.db import models
    2 
    3 from django.contrib.auth.models import AbstractUser
    4 
    5 
    6 class Userinfo(AbstractUser):
    7 
    8     email = models.EmailField()
    models.py

     

    seetings.py

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

     

    views.py

      1 from django.shortcuts import render, HttpResponse, redirect
      2 from django import forms
      3 from django.core.validators import RegexValidator
      4 from django.core.exceptions import ValidationError
      5 import re
      6 from app01 import models
      7 from django.http import JsonResponse
      8 from django.urls import reverse
      9 from django.contrib import auth
     10  
     11 # Create your views here.
     12  
     13 def name_valid(value):
     14     name_re = re.compile(r'^[d]+')
     15     ret = name_re.match(value)
     16     if ret:
     17         raise ValidationError('用户名不能以数字开头!')
     18  
     19 class RegisterForm(forms.Form):
     20     name = forms.CharField(
     21         required=True,
     22         label='用户名:',
     23         min_length=6,
     24         max_length=32,
     25         help_text='只能有字母数字下划线组成,且不能以数字开头,长度6到32位!',
     26         # initial='admin123_',
     27         error_messages={
     28             'required': '用户名不能为空!',
     29             'min_length': '长度不能少于6位!',
     30             'max_length': '长度不能超过32位!',
     31         },
     32         validators=[RegexValidator(r'^[a-zA-Z0-9_]+$', '用户名只能包含字母数字下划线!'), name_valid],
     33     )
     34     password = forms.CharField(
     35         required=True,
     36         label='密码:',
     37         min_length=6,
     38         max_length=32,
     39         help_text='长度6到32位!',
     40         initial='',
     41         error_messages={
     42             'required': '密码不能为空!',
     43             'min_length': '长度不能少于6位!',
     44             'max_length': '长度不能超过32位!',
     45         },
     46         widget=forms.PasswordInput(render_value=True),
     47     )
     48     r_password = forms.CharField(
     49         required=True,
     50         label='确认密码:',
     51         min_length=6,
     52         max_length=32,
     53         help_text='长度6到32位!',
     54         initial='',
     55         error_messages={
     56             'required': '密码不能为空!',
     57             'min_length': '长度不能少于6位!',
     58             'max_length': '长度不能超过32位!',
     59         },
     60         widget=forms.PasswordInput(render_value=True),
     61     )
     62     email = forms.EmailField(
     63         required=True,
     64         label='邮箱',
     65         error_messages={
     66             'required': '邮箱不能为空!',
     67         }
     68     )
     69  
     70     def __init__(self, *args, **kwargs):
     71         super(RegisterForm, self).__init__(*args, **kwargs)
     72         for field in self.fields:
     73             self.fields[field].widget.attrs.update({'class': 'form-control'})
     74  
     75     def clean_name(self):
     76         pass
     77         return self.cleaned_data.get('name')
     78  
     79     def clean_password(self):
     80         pass
     81         return self.cleaned_data.get('password')
     82  
     83     def clean_r_password(self):
     84         pass
     85         return self.cleaned_data.get('r_password')
     86  
     87     def clean_email(self):
     88         pass
     89         return self.cleaned_data.get('email')
     90  
     91     def clean(self):
     92         password = self.cleaned_data.get('password')
     93         r_password = self.cleaned_data.get('r_password')
     94         if password != r_password:
     95             self.add_error('r_password', '两次密码不一致!')
     96             raise ValidationError('两次密码不一致!')
     97         else:
     98             return self.cleaned_data
     99  
    100  
    101 # 注册
    102 def register(request):
    103     if request.method == 'GET':
    104         register_obj = RegisterForm()
    105         return render(request, 'register.html', {'register_obj': register_obj})
    106     elif request.method == 'POST':
    107         data = request.POST
    108         # print(data)
    109         register_obj = RegisterForm(data)
    110         if register_obj.is_valid():
    111             user_obj = register_obj.cleaned_data
    112             print(user_obj)
    113             username = user_obj.get('name')
    114             password = user_obj.get('password')
    115             email = user_obj.get('email')
    116  
    117             if not models.Userinfo.objects.filter(username=username).exists():
    118                 new_obj = models.Userinfo.objects.create_user(username=username, password=password, email=email)
    119                 print(f'新用户{username}注册成功!')
    120                 return redirect('login')
    121             else:
    122                 register_obj.add_error('name', '用户名已存在!')
    123                 return render(request, 'register.html', {'register_obj': register_obj})
    124         else:
    125             return render(request, 'register.html', {'register_obj': register_obj})
    126 # 登录
    127 def login(request):
    128     if request.method == 'GET':
    129         return render(request, 'login.html')
    130     elif request.method == 'POST':
    131         # print(request.POST)
    132         username = request.POST.get('username')
    133         password = request.POST.get('password')
    134  
    135         user_obj = auth.authenticate(username=username, password=password)
    136         print(user_obj)
    137         if user_obj:
    138             auth.login(request, user_obj)
    139             return JsonResponse({'status': 1, 'url': reverse('index')})
    140         else:
    141             return JsonResponse({'status': 0, 'url': ''})
    142  
    143 #访问认证
    144 def index(request):
    145     if request.user.is_authenticated:
    146         print(request.user)
    147         if request.method == 'GET':
    148             return render(request, 'index.html')
    149     else:
    150         return redirect('login')
    151  
    152 #注销
    153 def logout(request):
    154     auth.logout(request)
    155     return redirect('login')
    156  
    157 #修改密码
    158 def reset_psd(request):
    159     if request.user.is_authenticated:
    160         if request.method == 'GET':
    161             return render(request, 'reset_psd.html')
    162         elif request.method == 'POST':
    163             old_password = request.POST.get('old_password')
    164             new_password = request.POST.get('new_password')
    165             r_new_password = request.POST.get('r_new_password')
    166             # ret=request.user.check_password(old_password)
    167             # print(ret)
    168             if request.user.check_password(old_password):
    169                 if new_password == r_new_password:
    170                     request.user.set_password(new_password)
    171                     request.user.save()
    172                     return JsonResponse({'status': True, 'info': '操作成功!', 'url': reverse('index')})
    173                 else:
    174                     return JsonResponse({'status': False, 'info': '两次新密码不一致!', 'url': ''})
    175             else:
    176                 return JsonResponse({'status': False, 'info': '操作失败:原密码输入有误!', 'url': ''})
    177         return JsonResponse({'status': False, 'info': '操作失败!', 'url': ''})
    178  
    179     else:
    180         return redirect('login')
    views.py

    urls.py

     1 from django.conf.urls import url
     2 from django.contrib import admin
     3 from app01 import views
     4  
     5 urlpatterns = [
     6     url(r'^admin/', admin.site.urls),
     7     url(r'^register/', views.register, name='register'),
     8     url(r'^login/', views.login, name='login'),
     9     url(r'^index/', views.index, name='index'),
    10     url(r'^logout/', views.logout, name='logout'),
    11     url(r'^reset_psd/', views.reset_psd, name='reset_psd'),
    12  
    13 ]
    14  
    urls.py

    templates

    register.html

     1 {% load static %}
     2 <!DOCTYPE html>
     3 <html lang="en">
     4 <head>
     5     <meta charset="UTF-8">
     6     <link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">
     7     <title>用户注册</title>
     8 </head>
     9 <body style="background-image: url('{% static 'images/register_bg.gif' %}');background-size: cover">
    10 <div class="container">
    11     <div class="row">
    12         <div class="col-xs-6 col-xs-offset-3" style="margin-top: 12%;">
    13             <div class="container-fluid" style="background-color: rgba(255,255,255,0.2);border-radius: 5%">
    14                 <div class="row">
    15                     <h2 class="text-left col-xs-8 text-primary">新用户注册:</h2>
    16                 </div>
    17                 <div class="row" >
    18                     <form action="{% url 'register' %}" method="post" novalidate class="form-horizontal">
    19                         {% csrf_token %}
    20                         {% for field in register_obj %}
    21                             <div class="form-group" >
    22                                 <label for="{{ field.id_for_label }}"
    23                                        class="col-xs-3 control-label" >{{ field.label }}</label>
    24                                 <div class="col-xs-7">
    25                                     {{ field }}
    26                                     <div style="height: 10px;" class="text-danger">{{ field.errors.0 }}</div>
    27                                 </div>
    28                             </div>
    29                         {% endfor %}
    30                         <div class="form-group">
    31                             <div class="col-sm-7  col-xs-offset-3">
    32                                 <span class="col-xs-10 text-success text-center"
    33                                       style="line-height: 200%">已有账号,请<a href="{% url 'login' %}">登录</a></span>
    34                                 <input type="submit" class="btn btn-success btn-sm col-xs-2 pull-right">
    35                             </div>
    36                         </div>
    37                     </form>
    38                 </div>
    39             </div>
    40         </div>
    41     </div>
    42 </div>
    43 </body>
    44 <script src="{% static 'jquery-3.4.1.js' %}"></script>
    45 <script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script>
    46 </html>
    register.html

    login.html

      1 {% load static %}
      2 <!DOCTYPE html>
      3 <html lang="en">
      4 <head>
      5     <meta charset="UTF-8">
      6     <link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">
      7     <title>用户登录</title>
      8 </head>
      9 <body style="background-image: url('{% static "images/login_bg.jpg" %}');background-size: cover">
     10 <div>
     11     <div class="container">
     12         <div class="row">
     13             <div class='col-xs-4 col-xs-offset-4'>
     14                 <div class="row" style="margin-top: 50%;background-color: rgba(255,255,255,0.2 );border-radius: 3%">
     15                     <div class="row c1">
     16                         <h2 class=" col-xs-6  text-primary" style="margin-bottom: 30px">用户登录</h2>
     17                     </div>
     18                     <div class="row">
     19                         <div class="form-group" style="height: 60px;">
     20                             <label for="username" class="col-xs-3 control-label text-right">用户名:</label>
     21                             <div class="col-xs-8">
     22                                 <input type="text" class="form-control" id="username">
     23                                 <div class="text-danger"></div>
     24                             </div>
     25                         </div>
     26                         <div class="form-group" style="height: 60px;">
     27                             <label for="password" class="col-xs-3 control-label text-right">密码:</label>
     28                             <div class="col-xs-8">
     29                                 <input type="password" class="form-control" id="password">
     30                                 <div class="text-danger"></div>
     31                             </div>
     32                         </div>
     33                         <div class="form-group" style="height: 60px;">
     34                             {% csrf_token %}
     35                             <div class="col-xs-8 col-xs-offset-3">
     36                                 <a href="{% url 'register' %}">
     37                                     <button class="btn btn-primary col-xs-offset-2" id="register">注册</button>
     38                                 </a>
     39                                 <button class="btn btn-success col-xs-offset-2" id="submit">登录</button>
     40                                 <div class=" text-danger"></div>
     41                             </div>
     42                         </div>
     43                     </div>
     44                 </div>
     45             </div>
     46         </div>
     47     </div>
     48 </div>
     49  
     50 </div>
     51 </div>
     52 </body>
     53 <script src="{% static 'jquery-3.4.1.js' %}"></script>
     54 <script src="{% static 'jquery-cookie-1.4.1.js' %}"></script>
     55 <script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script>
     56 <script>
     57     $(function () {
     58         $('#username').blur(function () {
     59            if(username !== ''){$('#username').next().text('');}
     60         });
     61         $('#password').blur(function () {
     62            if(username !== ''){$('#password').next().text('');}
     63         });
     64         $('#username').focus(function () {
     65            if(username !== ''){$('#submit').next().text('');}
     66         });
     67         $('#password').focus(function () {
     68            if(username !== ''){$('#submit').next().text('');}
     69         });
     70  
     71  
     72         $('#submit').click(function () {
     73  
     74             var username = $('#username').val().trim();
     75             var password = $('#password').val().trim();
     76  
     77  
     78             if (username === '' || password === '') {
     79                 if (username === '') {
     80                     $('#username').next().text('用户名不能为空!');
     81                 }
     82                 ;
     83                 if (password === '') {
     84                     $('#password').next().text('密码不能为空!')
     85                 }
     86                 ;
     87  
     88             } else {
     89                 $.ajax({
     90                     url: '{% url 'login' %}',
     91                     type: 'POST',
     92                     headers: {'X-CSRFToken': $.cookie('csrftoken')},
     93                     data: {
     94                         'username': username,
     95                         'password': password,
     96  
     97                     },
     98                     success: function (request) {
     99                         console.log(request);
    100                         if (request.status === 1) {
    101                             location.href = request.url;
    102                         } else {
    103                             $('#submit').next().text('账号或密码有误!');
    104                         }
    105                     }
    106  
    107                 })
    108             }
    109  
    110         })
    111     })
    112 </script>
    113 </html>
    114  
    login.html

    index.html

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>首页</title>
     6 </head>
     7 <body>
     8 <h1>index</h1>
     9 <a href="{%  url 'logout' %}"><h6>注销</h6></a>
    10 <a href="{% url 'reset_psd' %}">修改密码</a>
    11 </body>
    12 </html>
    index.html

    reset_psd.html

     1 {% load static %}
     2 <!DOCTYPE html>
     3 <html lang="en">
     4 <head>
     5     <meta charset="UTF-8">
     6     <link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">
     7     <title>修改密码</title>
     8 </head>
     9 <body>
    10 <div><h3>当前用户:{{ username }}</h3>
    11         <p>请输入原密码:<input type="password" id="old_password"></p>
    12         <P>请输入新密码:<input type="password" id="new_password"></P>
    13         <p>请确认新密码:<input type="password" id="r_new_password"></p>
    14         {% csrf_token %}
    15         <p><button class="btn btn-success" id="submit">保存</button></p>
    16     </form>
    17 </div>
    18 </body>
    19 <script src="{% static 'jquery-3.4.1.js' %}"></script>
    20 <script src="{% static 'jquery-cookie-1.4.1.js' %}"></script>
    21 <script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script>
    22 <script>
    23     $(function () {
    24         $('#submit').click(function () {
    25             var old_password=$('#old_password').val().trim();
    26             var new_password=$('#new_password').val().trim();
    27             var r_new_password=$('#r_new_password').val().trim();
    28  
    29             if(old_password===''||new_password==='' || r_new_password===''){
    30                 alert('不允许有空!');
    31                 return false
    32             };
    33  
    34             if(new_password!==r_new_password){
    35                 alert('两次输入的新密码不一致,请重新确认输入!');
    36                 return false
    37             };
    38             $.ajax({
    39                 url:'{% url "reset_psd" %}',
    40                 type:'post',
    41                 headers:{'X-CSRFToken':$.cookie('csrftoken')},
    42                 data:{
    43                     old_password:old_password,
    44                     new_password:new_password,
    45                     r_new_password:r_new_password,
    46                 },
    47                 success:function (response) {
    48                     if(response.status===true){
    49                         alert(response.info);
    50                         location.href=response.url;
    51                     }
    52                     else {
    53                         alert(response.info)
    54                     }
    55                 }
    56             }
    57             )
    58         })
    59     })
    60 </script>
    61 </html>
    reset_psd.hml

     

     

     

     

  • 相关阅读:
    webService客户端搭建(三)
    webService服务器端搭建(二)
    electron 编译 sqlite3避坑指南---尾部链接有已经编译成功的sqlite3
    解决网页中Waiting (TTFB)数据加载过慢的问题
    Node-sqlite3多字段插入数据问题
    win上使用nvm管理node版本
    centos系统设置局域网静态IP
    将win平台上的mysql数据复制到linux上报错Can't write; duplicate key in table
    win上配置nginx
    Nodejs解决所有跨域请求
  • 原文地址:https://www.cnblogs.com/open-yang/p/11223250.html
Copyright © 2011-2022 走看看