Django认证系统实现的web页面实现代码


Posted in Python onAugust 12, 2019

结合数据库、ajax、js、Djangoform表单和认证系统的web页面

一:数据模块

扩展了Django中的user表,增加了自定义的字段

from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class UserInfo(AbstractUser):
 phone = models.CharField(max_length=11)
 gender = models.CharField(max_length=2)

二:路由系统

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),
 url(r'^login/',views.login_view),
 url(r'^home/',views.home),
 url(r'^logout/',views.logout_view),
 url(r'^modify_pwd/',views.modify_pwd),
 url(r'^$',views.home),
]

三:视图系统

from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.contrib.auth import authenticate, login,logout
from app01 import forms
from app01.models import UserInfo
# Create your views here.
def register(request):
 form_obj = forms.Reg_form()
 if request.method == 'POST':
  form_obj = forms.Reg_form(request.POST)
  if form_obj.is_valid():
   info_dic = form_obj.cleaned_data
   sex_dic = {'1':'男','2':'女','3':'保密'}
   info_dic['gender']=sex_dic[info_dic['gender']]

   UserInfo.objects.create_user(
    username=info_dic['username'],
    password = info_dic['pwd'],
    gender=info_dic['gender'],
    phone =info_dic['phone']
   )
   return redirect('/login/')
 return render(request, "register.html",{'form_obj':form_obj})


def login_view(request):
 if request.method == 'POST':
  username = request.POST.get('username')
  pwd = request.POST.get('pwd')
  user = authenticate(username=username, password=pwd)
  if user:
   login(request, user)
   data = {'code':1}
  else:
   data = {'code': 0,'msg':'用户名或密码错误'}
  return JsonResponse(data)
 return render(request, 'login.html')


@login_required
def logout_view(request):
 logout(request)
 return redirect('/login/')

@login_required
def home(request):
 user_id = request.session['_auth_user_id']
 use_obj = request.user
 return render(request,'home.html',{'user':use_obj})

@login_required
def modify_pwd(request):
 if request.method == 'POST':
  old_pwd = request.POST.get('old_pwd')
  pwd = request.POST.get('pwd')
  re_pwd = request.POST.get('re_pwd')
  user_obj = request.user
  if user_obj.check_password(old_pwd):
   if re_pwd == pwd:
    user_obj.set_password(pwd)
    user_obj.save()
    data = {'code': 1}
   else:
    data = {'code': 0, 'msg': '两次输入密码不一致'}
  else:
   data = {'code': 0, 'msg': '原始密码输入错误'}
  return JsonResponse(data)
 return render(request,'modify_pwd.html')

四:form表单

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Author:YiJun
from django import forms
from app01 import models
from django.forms import widgets
from django.core.exceptions import ValidationError # 导入异常
import re
# Create your views here.
class Reg_form(forms.Form):
 # 用户名表单
 username = forms.CharField(
  min_length=4,
  label="设置用户名",
  error_messages={
   "required": "不能为空",
   "invalid": "格式错误",
   "min_length": "用户名最少4个字符"
  },
  widget=widgets.TextInput(
   attrs={
    'class': "form-control",
    'placeholder': '用户名'
   })
 )
 # 用户密码设置表单
 pwd = forms.CharField(
  min_length=6,
  label="设置密码",
  widget=forms.widgets.PasswordInput(
   attrs={
    'class': 'form-control',
    'placeholder': '密码'},
   render_value=True,
  ),
  error_messages={
   "required": "不能为空",
   "invalid": "格式错误",
   "min_length": "密码至少6位"

  }
 )
 # 用户密码确认表单
 r_pwd = forms.CharField(
  min_length=6,
  label="确认密码",
  widget=forms.widgets.PasswordInput(
   attrs={
    'class': 'form-control',
    'placeholder': '确认密码'},
   render_value=True,
  ),
  error_messages={
   "required": "不能为空",
   "invalid": "格式错误",
   "min_length": "密码至少6位"

  }
 )
 # 用户性别选择表单
 gender = forms.ChoiceField(
  choices=((1, "男"), (2, "女"), (3, "保密")),
  label="性别",
  initial=3,
  widget=forms.widgets.RadioSelect
 )
 # 用户手机号码表单
 phone = forms.CharField(
  label="手机号码",
  max_length=11,
  min_length=11,
  error_messages={
   "required": "不能为空",
   "invalid": "格式错误",
   "min_length": "手机号码至少11位",
   "max_length": "手机号码最多11位",
  },
  widget=widgets.TextInput(attrs={'class': "form-control",'placeholder': '手机号码'})
 )

 def clean_phone(self):
  value = self.cleaned_data['phone']
  expression = re.compile('^1[3589][0-9]{9}')
  if not expression.search(value).group():
   raise ValidationError('请输入正确的手机号码')
  else:
   return value
 def clean_username(self):
  value = self.cleaned_data['username']
  if models.UserInfo.objects.filter(username=value):
   raise ValidationError('用户名已经注册')
  else:
   return value
 def clean(self):
  pwd = self.cleaned_data.get("pwd")
  r_pwd = self.cleaned_data.get("r_pwd")
  if pwd != r_pwd:
   self.add_error("r_pwd", "两次输入的密码不一致!")
   # 两次输入的密码不一致
   raise ValidationError("两次输入的密码不一致!")
  else:
   self.cleaned_data.pop('r_pwd')
   return self.cleaned_data

五:模板系统

注册页面

<!doctype html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport"
   content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.min.css" rel="external nofollow" >
 <title>Document</title>
</head>
<body>
<div class="container">
 <div class="row" style="margin-top: 50px">
  <div class="panel panel-primary">

   <div class="panel-heading"><h4>用户详细信息</h4></div>
   <div class="panel-body">

   </div>

   <!-- Table -->
   <div class="table-responsive">
    <table class="table table-bordered">
     <thead>
     <tr>
      <th>#</th>
      <th>用户名</th>
      <th>手机号码</th>
      <th>上次登陆时间</th>
      <th>注册时间</th>
      <th>用户性别</th>
     </tr>
     </thead>
     <tbody>
     <tr>
      <th scope="row">1</th>
      <td>{{ user.username }}</td>
      <td>{{ user.phone }}</td>
      <td>{{ user.last_login|date:'Y-m-d H:i:s' }}</td>
      <td>{{ user.date_joined|date:'Y-m-d H:i:s' }}</td>
      <td>{{ user.gender }}</td>
     </tr>
     </tbody>
    </table>
   </div>
  </div>
  <div style="margin-top: 20px">
   <a class="btn btn-info " href="/modify_pwd/" rel="external nofollow" >修改密码</a>
   <a class="btn btn-danger pull-right" href="/logout/" rel="external nofollow" >注销</a>
  </div>
 </div>
</div>
<script src="/static/jquery-3.3.1.min.js"></script>
<script src="/static/bootstrap-3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
home.html

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
用Python实现命令行闹钟脚本实例
Sep 05 Python
Python 获取当前所在目录的方法详解
Aug 02 Python
深入理解Python单元测试unittest的使用示例
Nov 18 Python
使用python爬取B站千万级数据
Jun 08 Python
IntelliJ IDEA安装运行python插件方法
Dec 10 Python
python 多个参数不为空校验方法
Feb 14 Python
Python Matplotlib实现三维数据的散点图绘制
Mar 19 Python
分享一个pycharm专业版安装的永久使用方法
Sep 24 Python
python zip,lambda,map函数代码实例
Apr 04 Python
Python实现Word表格转成Excel表格的示例代码
Apr 16 Python
Python 中由 yield 实现异步操作
May 04 Python
Python 操作 MySQL数据库
Sep 18 Python
django 自定义过滤器(filter)处理较为复杂的变量方法
Aug 12 #Python
django-filter和普通查询的例子
Aug 12 #Python
利用python实现汉字转拼音的2种方法
Aug 12 #Python
python面向对象 反射原理解析
Aug 12 #Python
Python中正反斜杠(‘/’和‘\’)的意义与用法
Aug 12 #Python
Django 查询数据库并返回页面的例子
Aug 12 #Python
python3 深浅copy对比详解
Aug 12 #Python
You might like
php多文件上传下载示例分享
2014/02/20 PHP
基于thinkPHP3.2实现微信接入及查询token值的方法
2017/04/18 PHP
jquery tools之tooltip
2009/07/25 Javascript
自己的js工具_Form 封装
2009/08/21 Javascript
jQuery .tmpl(), .template()学习资料小结
2011/07/18 Javascript
JS实现标签页效果(配合css)
2013/04/03 Javascript
js判断文本框剩余可输入字数的方法
2015/02/04 Javascript
简单谈谈node.js 版本控制 nvm和 n
2015/10/15 Javascript
AngularJS中$interval的用法详解
2016/02/02 Javascript
探讨:JavaScript ECAMScript5 新特性之get/set访问器
2016/05/05 Javascript
jQuery中实现prop()函数控制多选框(全选,反选)
2016/08/19 Javascript
js style.display=block显示布局错乱问题的解决方法
2016/09/21 Javascript
AngularJS的ng-click传参的方法
2017/06/19 Javascript
微信小程序 Buffer缓冲区的详解
2017/07/06 Javascript
在Js页面通过POST传递参数跳转到新页面详解
2017/08/25 Javascript
vue-cli如何引入bootstrap工具的方法
2017/10/19 Javascript
IntelliJ IDEA 安装vue开发插件的方法
2017/11/21 Javascript
vue+springboot实现项目的CORS跨域请求
2018/09/05 Javascript
基于 vue-skeleton-webpack-plugin 的骨架屏实战
2019/08/05 Javascript
Python 匹配任意字符(包括换行符)的正则表达式写法
2009/10/29 Python
Python使用Socket(Https)Post登录百度的实现代码
2012/05/18 Python
Python爬取网易云音乐热门评论
2017/03/31 Python
python实现基于SVM手写数字识别功能
2020/05/27 Python
Pycharm无法显示动态图片的解决方法
2018/10/28 Python
分享Python切分字符串的一个不错方法
2018/12/14 Python
Python3 执行系统命令并获取实时回显功能
2019/07/09 Python
Flask框架单例模式实现方法详解
2019/07/31 Python
使用浏览器访问python写的服务器程序
2019/10/10 Python
python中wx模块的具体使用方法
2020/05/15 Python
Python系统公网私网流量监控实现流程
2020/11/23 Python
python爬虫如何解决图片验证码
2021/02/14 Python
高街生活方式全球在线商店:AZBRO
2017/08/26 全球购物
2014年学生会个人工作总结
2014/11/07 职场文书
公司介绍信范文
2015/01/31 职场文书
会计入职心得体会
2016/01/22 职场文书
Python scrapy爬取起点中文网小说榜单
2021/06/13 Python