---------------------------------------------前端页面简易代码-------------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册</title>
<script src="/static/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
<style>
#img_head {
display: none;
}
</style>
</head>
<body>
<div class="container-fluid box">
<h1></h1>
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Register</h3>
</div>
<div class="panel-body">
<form id="form">
{% csrf_token %}
{% for foo in my_form %}
<div class="form-group">
<label for="{{ foo.auto.id }}">{{ foo.label }}</label>
<span class="{{ foo.auto_id }} pull-right" style="color: red" id="span"></span>
{{ foo }}
</div>
{% endfor %}
{# 上传头像 #}
<div class="form-group">
<label for="img_head">头像
<img src="/static/img/default.png" alt="" width="80" height="80" id="my_head">
</label>
<input type="file" id="img_head" class="form-control">
</div>
</form>
<input type="button" value="注册" class="btn btn-primary pull-right" id="btn">
<span id="valid_code_error" class="pull-left" style="color: red"></span>
</div>
</div>
</div>
</div>
</div>
</body>
<script>
//上传头像,在注册页面显示
$('#img_head').change(function () {
var file_obj = $('#img_head')[0].files[0];
var filereader = new FileReader();
filereader.readAsDataURL(file_obj);
filereader.onload = function () {
$('#my_head').attr('src', filereader.result)
}
});
$('#btn').click(function () {
var formdata = new FormData();
var arr = $('#form').serializeArray();
{#console.log(arr);#}
$.each(arr, function (key, obj) {
formdata.append(obj.name, obj.value)
});
formdata.append('img_head', $('#img_head')[0].files[0]);
{#console.log(arr);#}
$.ajax({
url: '/register/',
type: 'post',
processData: false,
contentType: false,
data: formdata,
success: function (data) {
if (data['msg'] == 100) {
window.location.href = "/index/"
} else if (data.msg['__all__']) {
$('#valid_code_error').html(data.msg['__all__'])
} else {
for (i in data.msg) {
console.log(i);
id = ".id_" + i;
console.log(data.msg[i][0]);
$(id).text(data.msg[i][0])
//上面的回调函数的内容为:产生不符合规范的注册信息,在注册页面显示出来
}
}
}
})
});
//失去焦点后,在注册页面产生的错误提示清空
$('#btn').blur(function () {
$(span).empty();
$('#valid_code_error').empty()
})
</script>
</html>
----------------------------------------------forms组件表-------------------------------------------------------------------------------
from django import forms
from django.forms import widgets
from django.core.exceptions import ValidationError
from app01 import models
class RegForm(forms.Form):
username = forms.CharField(max_length=16,min_length=3,label='用户名',
widget=widgets.TextInput(attrs={'class':'form-control'}),
error_messages={'max_length': '最长是16', 'min_length': '最短是3', 'required': '这个必须填'})
password = forms.CharField(max_length=16,min_length=3,label='密码',
widget=widgets.PasswordInput(attrs={'class':'form-control'}),
error_messages={'max_length': '最长是16', 'min_length': '最短是3', 'required': '这个必须填'})
re_password = forms.CharField(max_length=16, min_length=3, label='确认密码',
widget=widgets.PasswordInput(attrs={'class': 'form-control'}),
error_messages={'max_length': '最长是16', 'min_length': '最短是3', 'required': '这个必须填'})
email = forms.EmailField(label='邮箱',widget=widgets.TextInput(attrs={'class': 'form-control'}),
error_messages={'required': '这个必须填', 'invalid': '不符合邮箱格式'})
# 局部钩子函数,校验用户在注册时,用户名存不存在
def clean_username(self):
name = self.cleaned_data.get('username')
# 去数据库校验
ret = models.UserInfo.objects.filter(username=name).first()
if ret:
raise ValidationError('用户名已存在')
return name
# 全局校验钩子函数,校验注册时两次输入的密码是否一致
def clean(self):
pwd = self.cleaned_data.get('password')
re_pwd = self.cleaned_data.get('re_password')
if pwd and re_pwd:
if pwd == re_pwd:
return self.cleaned_data
else:
raise ValidationError('两次密码不一致')
-----------------------------注册views视图函数-----------------------------------------------------
from django.http import JsonResponse
from app01 import myforms
from app01 import models
def register(request):
if request.method == 'GET':
my_form = myforms.RegForm()
return render(request,'register.html',locals())
# elif request.is_ajax(): 方法一---判断request的提交方式.
elif request.method == 'POST': #方法二
response = {'status': 100, 'msg': 100}
print(request.POST)
my_form = myforms.RegForm(request.POST)
if my_form.is_valid():
dic = my_form.cleaned_data
dic.pop('re_password')
my_file = request.FILES.get('img_head')
if my_file:
dic['avatar']=my_file
user = models.UserInfo.objects.create_user(**dic)
else:
response['status']=101
response['msg']=my_form.errors
return JsonResponse(response)
补充:可以在前段js代码中单独加每一项注册内容是否合规
前台 ------ 用户名是否存在
$("#id_username").blur(function () {
$.ajax({
url:'/check_username/',
type:'post',
//name加引号不加引号都可以
data:{name:$(this).val(),'csrfmiddlewaretoken':'{{ csrf_token }}'},
success:function (data) {
console.log(data)
if(data.status==101){
$('#id_username').next().html(data.msg).parent().addClass('has-error')
}
}
})
})
后台判断逻辑
def check_username(request):
response={'status':100,'msg':None}
name=request.POST.get('name')
print(name)
user=models.UserInfo.objects.filter(username=name).first()
if user:
response['status']=101
response['msg']='用户名已被占用'
return JsonResponse(response)