views视图文件
实现用户注册
页面主要功能包括:
在页面中输入用户ID时,可实时监测ID是否可用
单击验证图片时,显示新的验证码
单击"提交"按钮时,依次检验用户ID,密码,e-mail地址是否可用。如果数据有错,在页面下方显示错误提示,在所有数据均有效时,将数据提交给服务器。
所有操作使用Ajax完成,不刷新页面。
#chapter7\newuser\views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template.response import TemplateResponse
from random import randint,choice
from PIL import Image,ImageDraw,ImageFont
from django.http import FileResponse
from .models import userinfo
def getRandomChar(): #获取随机字符
num =str(randint(0,9)) #获得随机数字
lower=chr(randint(97,122)) #获得随机小写字母
upper=chr(randint(65,90)) #获得随机大写字母
char=choice([num,lower,upper]) #选择要使用的随机字符
return char
def createImg(request): #创建验证码图片返回
img=Image.new(mode="RGB",size=(160,30),color=(100,100,100)) #创建图片
draw=ImageDraw.Draw(img) #获取图片画笔,用于描绘字
#设置字体,字体文件在项目同名子文件夹中
font=ImageFont.truetype(font="arial.ttf",size=24)
code=''
for i in range(5):
c=getRandomChar() #获得随机字符
draw.text((10+30*i,2),text=c,fill=(255,255,255),font=font)#根据坐标填充文字
code+=c #记录验证码字符
request.session['randomcode']=code #将验证码存入session
f=open("temp.png",'wb')
img.save(f, format="png")
f.close()
return FileResponse(open("temp.png",'rb'))
def doCheckUid(request):
ps=userinfo.objects.filter(uid=request.GET['uid'])
if ps.count()==0:
msg='ID可用'
else:
msg='ID已占用'
return HttpResponse(msg, content_type="text/text;charset=utf-8")
def returnCheckCode(request):
return HttpResponse(request.session['randomcode'], content_type="text/text;charset=utf-8")
def doAddNew(request):
try:
nuid = request.GET['uid']
pwd = request.GET['pwd']
nemail = request.GET['email']
user=userinfo(uid=nuid,password=pwd,email=nemail)
user.save()
msg="已成功完成注册!"
return HttpResponse(msg, content_type="text/text;charset=utf-8")
except Exception as e:
msg="意外出错:%s" % e
return HttpResponse(msg, content_type="text/text;charset=utf-8")
def toAddNew(request):
return render(request,'newuser.html')
models文件
from django.db import models
# Create your models here.
class userinfo(models.Model):
uid=models.CharField(max_length=10)
password=models.CharField(max_length=8)
email=models.CharField(max_length=20)
模板文件newuser.html
<!--chapter7\newuser\templates\newuser.html-->
<!DOCTYPE html>
<html>
<head><script src="/static/jquery-3.4.1.min.js"></script></head>
<body>
<center>
新用户注册<hr>
<table>
<tr><td align="right"> 用户ID:</td>
<td><input type="text" id="uid" maxlength="10">
<span id="ruid"></span>
</td></tr>
<tr><td align="right">密码:</td>
<td><input type="password" id="pwd1" maxlength="8"></td></tr>
<tr><td align="right">再次输入密码:</td>
<td><input type="password" id="pwd2" maxlength="8"></td></tr>
<tr><td align="right">Email:</td>
<td><input type="email" id="email" maxlength="20"></td></tr>
<tr><td align="right">验证码:</td>
<td><img src="/getpng/" id="icode" />单击刷新<br />
<input type="text" id="code" maxlength="10"></td></tr>
<tr><td colspan="2" align="center"><input type="button" value="提交" id="submit" /></td></tr>
</table>
<hr><span id="result"></span>
</center>
<script>
var codeok = false
var idok = false
$(document).ready(function () {
$('input').keyup(function () {//在输入数据时,清除上次的验证信息
$('#result').html('') });
$('#uid').keyup(function () {//在输入数据时,检查用户用户名是否可用
var uid = $("#uid").val();
$.get("/checkuid/", { 'uid': uid }, function (r) {
if (r == 'ID可用') { idok = true } else { idok = false }
$('#ruid').html(r) })
});
$('#icode').click(function () {//单击时更改图片src,
var a = (new Date()).toTimeString()
$('#icode').attr('src', '/getpng/?t=' + a) //加上不同的参数,以便刷新图片
codeok = false });
$('#code').blur(function () {//结束输入验证码时验证是否正确
var code = $("#code").val();
$.get("/checkcode/", {}, function (r) {
if (r.toLowerCase() == code.toLowerCase()) { codeok = true } else { codeok = false }
})
});
$('#submit').click(function () {//单击提交按钮时,先检查数据,通过后提交服务器
if (!idok) {
$('#result').html('<span style="color:red">你输入的用户ID已被占用!</span>')
return 1 }
var pwd1 = $("#pwd1").val();
var pwd2 = $("#pwd2").val();
pwdok = false
if (pwd1 != pwd2) {
$('#result').html('<span style="color:red">两次输入的密码不一致!</span>')
return 1}
var reg = /^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/;
if (!reg.test($("#email").val())) {
$('#result').html('<span style="color:red">你输入的Email地址无效!</span>')
return 1}
if (!codeok) {
$('#result').html('<span style="color:red">验证码输入错误!</span>')
return 1}
var uid = $("#uid").val();
var pwd = $("#pwd1").val();
var email = $("#email").val();
var data = { 'uid': uid, 'pwd': pwd, 'email': email }
$.get("/addnew/", { 'uid': uid, 'pwd': pwd, 'email': email }, function (r) { $('#result').html(r) })
});
});
</script>
</body>
</html>
urls文件
from django.contrib import admin
from django.urls import path
from app import views
from newuser import views as newuser_views
urlpatterns = [
path('admin/', admin.site.urls),
path('getdata/',views.getdata),
path('dform/',views.useDataForm),
path('dform3/',views.useDataForm3),
path('dyfield/',views.testcharForm),
path('dyfor/',views.testfor),
path('formset/',views.testformsetfactory),
path('modelform/',views.usepersonForm),
path('mdiy/',views.userPersonFromDIY),
path('media/',views.userPersonFromDIY_media),
path('first/',views.getinfofirst),
path('getinfo/',views.getPersonInfo),
path('getpng/', newuser_views.createImg),
path('checkuid/', newuser_views.doCheckUid),
path('checkcode/', newuser_views.returnCheckCode),
path('newfirst/', newuser_views.toAddNew),
path('addnew/', newuser_views.doAddNew),
]
ajax案例.png
ajax案例2.png
网友评论