登录功能
视图函数
def my_login(request):
if request.method == 'GET':
return render(request, 'login.html')
else:
name = request.POST.get('name')
password = request.POST.get('password')
code_text = request.POST.get('text')
text = request.session.get('code_text')
text = text.lower()
user = authenticate(request, username=name, password=password)
if user:
if not text:
return HttpResponse('验证码不能为空')
if code_text == text:
login(request, user)
return HttpResponse('登录成功')
else:
return HttpResponse('验证码错误')
else:
return HttpResponse('用户名或密码错误')
前端页面:
<form>
{% csrf_token %}
<h2>登录界面</h2>
<hr>
<div class="form-group">
<label for="name">用户名</label>
<input type="text" name="name" id="name" class="form-control" placeholder="用户名" required>
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" name="password" id="password" class="form-control" placeholder="密码" required>
</div>
<div class="form-group">
<label for="valid_code">验证码</label>
<div class="row">
<div class="col-md-6">
<input type="text" name="valid_code" id="valid_code" class="form-control" required>
</div>
<img src="/get_code/" alt="" width="50%" height="35" id="img_code" draggable="false">
</div>
</div>
</form>
<a href="/register/" class="btn btn-primary pull-left">注册</a>
<button type="button" class="btn btn-primary pull-right" id="btn">登录</button>
<a href="#" id="change" draggable="false" class="change pull-right">看不清,换一张</a>
<script>
$('#btn').click(function () {
$.ajax({
url: '/login/',
type: 'post',
data: {
'csrfmiddlewaretoken': $('[name="csrfmiddlewaretoken"]').val(),
'name': $('#name').val(),
'password': $('#password').val(),
'text': $('#valid_code').val()
},
success: function (data) {
alert(data)
}
})
});
$('#change').click(function () {
$('#img_code')[0].src += '?'
})
</script>
注册功能
froms组件
class MyForms(forms.Form):
username = forms.CharField(max_length=18, min_length=2, label='用户名',
error_messages={'max_length': '最长不超过18位', 'min_length': '最短为2个字符', 'required': '不能为空'},
widget=widgets.TextInput(attrs={'class': 'form-control', 'placeholder': '用户名'}))
password = forms.CharField(max_length=18, min_length=2, label='密码',
error_messages={'max_length': '最长不超过18位', 'min_length': '最短为2个字符', 'required': '不能为空'},
widget=widgets.PasswordInput(attrs={'class': 'form-control', 'placeholder': '密码'}))
re_password = forms.CharField(max_length=18, min_length=2, label='确认密码',
error_messages={'max_length': '最长不超过18位', 'min_length': '最短为2个字符',
'required': '不能为空'},
widget=widgets.PasswordInput(attrs={'class': 'form-control', 'placeholder': '确认密码'}))
email = forms.EmailField(label='邮箱', error_messages={'invalid': '不符合邮箱格式', 'required': '不能为空'},
widget=widgets.EmailInput(attrs={'class': 'form-control', 'placeholder': '邮箱'}))
def clean_username(self):
name = self.cleaned_data.get('username')
user = models.UserInfo.objects.filter(username=name).first()
if user:
raise ValidationError('用户名已存在')
else:
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('两次密码不一致')
视图函数
def my_register(request):
if request.method == 'GET':
myforms = MyForms()
return render(request, 'register.html', locals())
if request.is_ajax():
response = {'status': 100, 'msg': None}
myforms = MyForms(request.POST)
if myforms.is_valid():
data = myforms.cleaned_data
data.pop('re_password')
my_file = request.FILES.get('myfile')
if my_file:
data['avatar'] = my_file
user = models.UserInfo.objects.create_user(**data)
else:
response['status'] = 101
response['msg'] = myforms.errors
return JsonResponse(response)
前端页面
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<form id="form">
<h2>注册界面</h2>
<hr>
{% csrf_token %}
{% for foo in myforms %}
<div class="form-group">
<label for="{{ foo.auto_id }}">{{ foo.label }}</label>
{{ foo }}
</div>
{% endfor %}
<div class="form-group">
<label for="myfile">头像<img src="/static/img/default.png" id="img_file" alt="" width="40"
height="40"></label>
<input type="file" id="myfile">
</div>
</form>
<button type="button" class="btn btn-primary pull-right" id="btn">提交</button>
</div>
</div>
</div>
</body>
<script>
// change为控件值发生变化时触发的事件
$('#myfile').change(function () {
// 取出文件
var file_obj = $('#myfile')[0].files[0];
// 生成文件阅读器对象,把获取的图片放到img
try{
var filereader = new FileReader();
// 把图片对象读入阅读器对象
filereader.readAsDataURL(file_obj);
// 等加载完毕后,渲染到img标签中
filereader.onload = function () {
// filereader.result获取阅读器对象中的值
$("#img_file").attr('src', filereader.result)
}
}catch (e) {
}
});
$('#btn').click(function () {
// 上传文件使用formdata对象
var formdata = new FormData();
var formarr = $('#form').serializeArray();
console.log(formarr);
// jquery循环 循环往formdata对象中添加数据
$.each(formarr, function (key, obj) {
formdata.append(obj.name, obj.value)
});
// 添加文件对象数据
formdata.append('myfile', $('#myfile')[0].files[0]);
$.ajax({
url: '/register/',
type: 'post',
processData: false,
contentType: false,
data: formdata,
success: function (data) {
if (data.status == '100'){
location.href = '/login/'
}else {
var msg = data.msg;
$('span').remove();
for (i in msg){
console.log(i,msg[i]);
if (i == '__all__'){
$('#id_re_password').after('<span class="pull-right">'+ msg[i] + '</span>')
}
$('#id_'+i).after('<span class="pull-right">'+ msg[i] + '</span>')
}
}
}
})
})
</script>
原文地址:https://www.cnblogs.com/louyefeng/p/10034359.html
时间: 2024-11-10 13:51:40