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根据开头和结尾字符串获取中间字符串的方法
Mar 26 Python
编写Python爬虫抓取豆瓣电影TOP100及用户头像的方法
Jan 20 Python
用python与文件进行交互的方法
Mar 01 Python
Python http接口自动化测试框架实现方法示例
Dec 06 Python
Python图像滤波处理操作示例【基于ImageFilter类】
Jan 03 Python
TensorFlow实现自定义Op方式
Feb 04 Python
在python中利用dict转json按输入顺序输出内容方式
Feb 27 Python
Python logging模块异步线程写日志实现过程解析
Jun 30 Python
Python如何定义接口和抽象类
Jul 28 Python
Python读写压缩文件的方法
Jul 30 Python
Visual Studio code 配置Python开发环境
Sep 11 Python
django使用多个数据库的方法实例
Mar 04 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
global.php
2006/12/09 PHP
php操作mysqli(示例代码)
2013/10/28 PHP
php实现专业获取网站SEO信息类实例
2015/04/02 PHP
PHP生成(支持多模板)二维码海报代码
2018/04/30 PHP
thinkphp5实现微信扫码支付
2019/12/23 PHP
JavaScript创建命名空间(namespace)的最简实现
2007/12/11 Javascript
web性能优化之javascript性能调优
2012/12/28 Javascript
js判断浏览器类型的方法
2013/08/07 Javascript
JavaScript之IE的fireEvent方法详细解析
2013/11/20 Javascript
jquery获取选中的文本和值的方法
2014/07/08 Javascript
ionic2懒加载配置详解
2017/09/01 Javascript
nodejs调取微信收货地址的方法
2017/12/20 NodeJs
基于Vue2.X的路由和钩子函数详解
2018/02/09 Javascript
详解Django中的ifequal和ifnotequal标签使用
2015/07/16 Python
Python利用IPython提高开发效率
2016/08/10 Python
Python基于scapy实现修改IP发送请求的方法示例
2017/07/08 Python
pandas表连接 索引上的合并方法
2018/06/08 Python
Python闭包和装饰器用法实例详解
2019/05/22 Python
Python获取、格式化当前时间日期的方法
2020/02/10 Python
Python3实现飞机大战游戏
2020/04/24 Python
学习python需要有编程基础吗
2020/06/02 Python
Django配置跨域并开发测试接口
2020/11/04 Python
Staples美国官方网站:办公用品一站式采购
2016/07/28 全球购物
小女主人连衣裙:Little Mistress
2017/07/10 全球购物
Prototype如何实现页面局部定时刷新
2013/08/06 面试题
技术学校毕业生求职信分享
2013/12/02 职场文书
酒店门卫岗位职责
2013/12/29 职场文书
高三学习决心书
2014/03/11 职场文书
开学典礼演讲稿
2014/05/23 职场文书
2014年学校领导班子对照检查材料
2014/09/19 职场文书
运动会稿件100字
2014/09/24 职场文书
学校体育节班级口号
2015/12/25 职场文书
《活见鬼》教学反思
2016/02/24 职场文书
详细总结Python常见的安全问题
2021/05/21 Python
Redis命令处理过程源码解析
2022/02/12 Redis
nginx日志格式分析和修改
2022/04/28 Servers