python day62
BBS项目(续)
注册功能前端
发送ajax请求,使用的Formdata
$('#id_submit').click(function () {
let formdata = new FormData()
formdata.append('myfile', $('#myfile')[0].files[0])
//方案一
/*
formdata.append('username',$('#id_username').val())
formdata.append('password',$('#password').val())
formdata.append('re_password',$('#id_re_password').val())
formdata.append('email',$('#id_email').val())
*/
//方案二
let form_data = $('#my_form').serializeArray()
//console.log(form_data)
$.each(form_data, function (index, element) {
//console.log(index)
//console.log(element)
formdata.append(element.name, element.value)
})
//console.log(formdata.get('username'))
$.ajax({
url: '/register/',
method: 'post',
contentType: false,
processData: false,
data: formdata,
success: function (data) {
console.log(data)
if (data.status == 100) {
location.href = data.next_url
//location.href='/login/'
} else {
$.each(data.msg, function (key, value) {
//console.log('#id_'+key)
if (key == '__all__') {
$('#id_error').html(value[0])
} else {
//取到input标签的下一个
//$('#id_'+key).next().html(value[0])
//链式调用
//$('#id_'+key).parent().addClass('has-error')
//链式调用
$('#id_' + key).next().html(value[0]).parent().addClass('has-error')
}
})
//加了一个定时器,3s以后干某些事
setTimeout(function () {
//清除红色框
$('.form-group').removeClass('has-error')
//清空所有错误信息
$('.error').html('')
}, 3000)
}
}
})
})
注册功能后端
def register(request):
if request.method == 'GET':
register_form = RegisterForm()
return render(request, 'register.html', context={'form': register_form})
elif request.method == 'POST':
response = {'status': 100, 'msg': None}
register_form = RegisterForm(request.POST)
if register_form.is_valid():
# 数据校验通过
# 可能传头像,可能没传头像
clean_data=register_form.cleaned_data
print(clean_data)
my_file=request.FILES.get('myfile')
if my_file: # 传了头像
# FileField字段类型直接接受一个文件对象,
# 它会把文件存到upload_to='avatar/',然后把路径存到数据库中
# 相当于with open 打开文件,把文件存到avatar路径下,把路径赋值给avatar这个字段
clean_data['avatar']=my_file
clean_data.pop('re_password')
models.UserInfo.objects.create_user(**clean_data)
response['msg']='恭喜你,注册成功'
response['next_url']='/login/'
else:
response['status']=101
response['msg'] = register_form.errors
return JsonResponse(response)
注册功能前端错误渲染
success: function (data) {
console.log(data)
if (data.status == 100) {
location.href = data.next_url
} else {
$.each(data.msg, function (key, value) {
if (key == '__all__') {
$('#id_error').html(value[0])
} else {
$('#id_' + key).next().html(value[0]).parent().addClass('has-error')
}
})
setTimeout(function () {
//清除红色框
$('.form-group').removeClass('has-error')
//清空所有错误信息
$('.error').html('')
}, 3000)
}
}
登录页面搭建
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面</title>
<link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
<script src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">登录功能</h3>
</div>
<div class="panel-body">
<form id="my_form">
{% csrf_token %}
<div class="form-group">
<label for="">用户名</label>
<input type="text" id="id_username" class="form-control">
<span class="danger pull-right error"></span>
</div>
<div class="form-group">
<label for="">密码</label>
<input type="text" id="id_password" class="form-control">
<span class="danger pull-right error"></span>
</div>
<div class="form-group">
<label for="">验证码</label>
<div class="row">
<div class="col-md-6">
<input type="text" id="id_code" class="form-control">
</div>
<div class="col-md-6">
<img src="/get_code/" alt="" height="35px" width="300px">
</div>
</div>
</div>
<div class="text-center">
<input type="button" value="登录" class="btn btn-warning" id="id_submit"><span
class="danger error"
id="id_error"
style="margin-left: 10px"></span>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
手写验证码(第三方)
生成验证码的模块(不需要自己写了)
https://www.jb51.net/article/153863.html
自己写
def get_random():
return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
def get_code(request):
# img = Image.new('RGB', (300, 30), get_random())
img = Image.new('RGB', (250, 30), (250, 250, 250))
# 第一个参数,是文字格式的文件,ttf格式,第二个参数是文字大小
img_font = ImageFont.truetype('./static/font/ss.TTF', 20)
# 拿到一个画板对象,把图片放到画板上,指定写的字的字体是什么
img_draw = ImageDraw.Draw(img)
# 在画板上写文字
# 随机生成5位 小写字母,大写字母,和数字
code = ''
for i in range(5):
low_char = chr(random.randint(97, 122))
up_char = chr(random.randint(65, 90))
number_char = str(random.randint(0, 9))
res = random.choice([low_char, up_char, number_char])
code += res
img_draw.text((20 + i * 40, 0), res, fill=get_random(), font=img_font)
print(code)
request.session['code'] = code
# 画点和线
# 画线和点圈
width = 250
height = 30
for i in range(5):
x1 = random.randint(0, width)
x2 = random.randint(0, width)
y1 = random.randint(0, height)
y2 = random.randint(0, height)
# 在图片上画线
img_draw.line((x1, y1, x2, y2), fill=get_random())
for i in range(20):
# 画点
img_draw.point([random.randint(0, width), random.randint(0, height)], fill=get_random())
x = random.randint(0, width)
y = random.randint(0, height)
# 画弧形
img_draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random())
bytes_io = BytesIO()
img.save(bytes_io, 'png') # 写到内存中,需要传format,图片格式
return HttpResponse(bytes_io.getvalue()) # 把内容读出来
验证码的刷新
$('#id_img').click(function () {
let img_url = $('#id_img')[0].src
$('#id_img')[0].src = img_url + '?'
})
登录功能前端
$('#id_submit').click(function () {
$.ajax({
url: '/login/',
method: 'post',
data: {
username: $('#id_username').val(),
password: $('#id_password').val(),
code: $('#id_code').val(),
csrfmiddlewaretoken:'{{ csrf_token }}'
},
success:function (data) {
if(data.status==100){
//location.href='/index/'
location.href=data.url
}else{
$('#id_error').html(data.msg)
}
}
})
})
登录功能后端
def login(request):
if request.method == 'GET':
return render(request, 'login.html')
else:
response = {'status': 100, 'msg': None}
username = request.POST.get('username')
password = request.POST.get('password')
code = request.POST.get('code')
if code.upper() == request.session.get('code').upper():
user = authenticate(username=username, password=password)
if user:
auth.login(request,user)
response['msg'] = '登录成功'
response['url'] = '/index/'
else:
response['status'] = 102
response['msg'] = '用户名或密码错误'
else:
response['status'] = 101
response['msg'] = '验证码错误'
return JsonResponse(response)