您现在的位置是: 网站首页 >Django >Django2.0.8+xadmin2实现在线学习网站 Django

【Django在线教育平台】18.个人中心修改邮箱及其他信息

admin2019年6月4日 14:18 Django | Html | JQuery 316人已围观

Django2.0.8+xadmin2实现在线学习网站简介 Django2.0.8+xadmin2实现在线学习网站,课程、讲师、机构、用户收藏功能。GitHub地址:https://github.com/xyliurui/OnlineLearningPlatform ;Django版本:2.0.8

## 个人中心修改邮箱功能 ### 发送邮箱验证码视图 ```python # 修改邮箱发送验证码 class ModifyEmailSendCodeView(LoginRequiredMixin, View): login_url = '/login/' redirect_field_name = 'next' def get(self, request): new_email = request.GET.get('new_email', '').strip() if new_email == '': return HttpResponse('{"email_status":"fail", "email_msg":"邮箱不能为空"}', content_type='application/json') elif UserProfile.objects.filter(email=new_email): return HttpResponse('{"email_status":"fail", "email_msg":"邮箱已存在"}', content_type='application/json') else: if send_register_email(request_uri=request.build_absolute_uri(), email=new_email, send_type='update_email'): return HttpResponse('{"email_status":"success", "email_msg":"邮件发送成功,请注意查收"}', content_type='application/json') else: return HttpResponse('{"email_status":"fail", "email_msg":"邮箱可能格式错误,发送失败"}', content_type='application/json') ``` ### email_send增加发送更新邮箱验证码 ```python def verify_email_format(email): p = re.compile('^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$') if p.match(email): return True else: return False # 发送注册邮件,发送之前先保存到数据库,到时候查询链接是否存在 def send_register_email(request_uri, email, send_type='register'): # 检查邮箱格式,格式不正确发送邮件返回False if not verify_email_format(email): return False # 实例化一个EmailVerifyRecord对象 email_record = EmailVerifyRecord() # 如果是修改邮箱,则发送4为验证码 if send_type == 'update_email': code = random_str(4) else: # 生成随机的code放入链接 code = random_str(16) email_record.code = code email_record.email = email email_record.send_type = send_type email_record.save() # 定义邮件内容 email_title = '' email_body = '' if send_type == 'register': email_title = '在线学习平台 注册激活链接' email_body = '请点击链接激活账号:{}active/{}'.format(request_uri, code) # request_uri='http://127.0.0.1:8000/register/' # 使用Django内置函数完成邮件发送。四个参数:主题,邮件内容,从哪里发,接受者list send_status = send_mail(email_title, email_body, settings.EMAIL_FROM, [email]) if send_status: return True else: return False elif send_type == 'forget': email_title = '在线学习平台 密码重置链接' email_body = '请点击链接重置密码:{}reset/{}'.format(request_uri, code) # request_uri='http://127.0.0.1:8000/forgetpwd/' # 使用Django内置函数完成邮件发送。四个参数:主题,邮件内容,从哪里发,接受者list send_status = send_mail(email_title, email_body, settings.EMAIL_FROM, [email]) if send_status: return True else: return False elif send_type == 'update_email': email_title = '在线学习平台 修改邮箱地址' email_body = '用户邮箱修改确认验证码:{} (区分大小写)'.format(code) # 使用Django内置函数完成邮件发送。四个参数:主题,邮件内容,从哪里发,接受者list send_status = send_mail(email_title, email_body, settings.EMAIL_FROM, [email]) if send_status: return True else: return False ``` ### 发送验证码url ```python from .views import UserCenterInfoView, UserModifypwdView, UserImageUploadView, ModifyEmailSendCodeView, SaveEmailModifyView app_name = 'users' urlpatterns = [ # 用户相关url path('info/', UserCenterInfoView.as_view(), name='user_info'), # 用户信息 path('password/modify/', UserModifypwdView.as_view(), name='user_modify_pwd'), # 修改密码 path('image/upload/', UserImageUploadView.as_view(), name='user_image_upload'), # 用户上传头像 path('verify_code/send/', ModifyEmailSendCodeView.as_view(), name='user_send_verify_code'), # 用户修改邮箱发送验证码 ] ``` ### 修改邮箱验证码模板,模态框 修改密码模态框点击[修改],然后弹出模态框 ```html <div class="form-group"> <label class="col-sm-2 control-label">邮&nbsp;&nbsp;&nbsp;&nbsp;箱</label> <div class="col-sm-8"> <input type="text" disabled="" name="email" value="{{ user.email }}" class="form-control"> </div> <div class="col-sm-2 control-label"> <a href="#" data-toggle="modal" data-target="#modifyEmailModal"><b>[ 修改 ]</b></a> </div> </div> ``` 修改密码模态框 ```html <!-- 修改邮箱模态框 --> <div class="modal fade padding-top-150" id="modifyEmailModal" tabindex="-1" role="dialog" aria-labelledby="modifyEmailModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> &times; </button> <h5 class="modal-title" id="modifyEmailLabel"> 邮箱修改 &nbsp;&nbsp; <small id="email_msg" style="color: red"></small> </h5> </div> <div class="modal-body"> <form class="form-horizontal" id="js_modify_email_form"> <div class="form-group"> <label class="col-sm-2 control-label">旧&nbsp;邮&nbsp;箱</label> <div class="col-sm-10" style="width: 80%"> <input type="text" class="form-control" value="{{ user.email }}" disabled> </div> </div> <div class="hr-line-dashed"></div> <div class="form-group"> <label class="col-sm-2 control-label">新&nbsp;邮&nbsp;箱</label> <div class="col-sm-10" style="width: 80%"> <input type="text" class="form-control" name='new_email' id="new_email" value="" placeholder="请输入新邮箱地址" required> </div> </div> <div class="hr-line-dashed"></div> <div class="form-group"> <label class="col-sm-2 control-label">验&nbsp;证&nbsp;码</label> <div class="col-sm-6"> <input type="text" class="form-control" name='code' value="" required> </div> <div class="col-sm-4 text-center"> <button type="button" class="btn-round" style="padding: 4px 10px;" id="send_email_button" onclick="send_email()">获取验证码</button> </div> </div> <div class="hr-line-dashed"></div> {% csrf_token %} </form> </div> <div class="modal-footer"> <div class="pro-btn"> <button type="button" class="btn-round btn-light" data-dismiss="modal" onclick="recovery_button()">关闭 </button> <button class="btn-round" id="js_modify_email_button"> 提交更改 </button> </div> </div> </div><!-- /.modal-content --> </div><!-- /.modal --> </div> ``` 发送邮箱验证码js ```html <script type="text/javascript"> //修改邮箱发送验证码 function send_email() { let new_email = document.getElementById('new_email').value; $.ajax({ cache: false, type: "GET", url: "{% url 'usercenter:user_send_verify_code' %}?new_email=" + new_email, dataType: "json", async: true, success: function (data) { document.getElementById('email_msg').innerText = data.email_msg; if (data.email_status === 'success') { $('#send_email_button').attr('disabled', true); // 发送邮件按钮变为不可点击 $('#send_email_button').html('已发验证码'); // 发送邮件文字修改 $('#new_email').attr('disabled', true); // 输入框变为不可输入 } else { $('#send_email_button').attr('disabled', false); // 邮件发送失败按钮可点击 $('#send_email_button').html('获取验证码'); // 发送邮件文字修改 $('#new_email').attr('disabled', false); // 输入框变为输入 } }, }); } //关闭修改邮箱模态框后,发送验证码变为可点击 function recovery_button() { $('#send_email_button').attr('disabled', false); // 邮件发送失败按钮可点击 $('#send_email_button').html('获取验证码'); // 发送邮件文字修改 $('#new_email').attr('disabled', false); // 输入框变为输入 } </script> ``` ![BLOG_20190604_141912_65](/media/blog/images/2019/06/BLOG_20190604_141912_65.png "博客图集BLOG_20190604_141912_65.png") ### 保存邮箱更改视图 ```python # 保存修改的邮箱 class SaveEmailModifyView(LoginRequiredMixin, View): login_url = '/login/' redirect_field_name = 'next' def post(self, request): new_email = request.POST.get('new_email', '').strip() verification_code = request.POST.get('code', '').strip() # 查询验证码是否存在 existed_record = EmailVerifyRecord.objects.filter(code=verification_code, email=new_email, send_type='update_email') if existed_record: user = request.user user.email = new_email user.save() return HttpResponse('{"save_email_status":"success", "save_email_msg":"邮箱已更新"}', content_type='application/json') else: return HttpResponse('{"save_email_status":"fail", "save_email_msg":"邮箱验证失败"}', content_type='application/json') ``` ### 保存邮箱修改url ```python from .views import UserCenterInfoView, UserModifypwdView, UserImageUploadView, ModifyEmailSendCodeView, SaveEmailModifyView app_name = 'users' urlpatterns = [ # 用户相关url path('info/', UserCenterInfoView.as_view(), name='user_info'), # 用户信息 path('password/modify/', UserModifypwdView.as_view(), name='user_modify_pwd'), # 修改密码 path('image/upload/', UserImageUploadView.as_view(), name='user_image_upload'), # 用户上传头像 path('verify_code/send/', ModifyEmailSendCodeView.as_view(), name='user_send_verify_code'), # 用户修改邮箱发送验证码 path('email_modify/save/', SaveEmailModifyView.as_view(), name='user_save_email_modify'), # 用户保存邮箱修改 ] ``` ### 保存邮箱修改js提交 ```html <script type="text/javascript"> //提交邮箱修改表单 $(function () { $('#js_modify_email_button').on('click', function () { $.ajax({ cache: false, type: 'POST', url: '{% url "usercenter:user_save_email_modify" %}', data: $('#js_modify_email_form').serialize(), async: true, beforeSend: function (XMLHttpRequest) { $('#send_email_button').val('发送中...'); $('#new_email').attr('disabled', true); // 输入邮箱禁用 $('#send_email_button').attr('disabled', true); // 发送验证码按钮禁用 $('#js_modify_email_button').html('验证中...'); }, success: function (data) { if (data.save_email_status === 'success') { window.location.reload(); $('#usercenter_msg').html(data.save_email_msg); } else if (data.save_email_status === 'fail') { $('#email_msg').html(data.save_email_msg); // 模态框顶部错误提示 setTimeout( "$('#js_modify_email_button').html('提交更改')", 1000 //按钮显示1s验证中,验证不通过就恢复 ); } }, }); }); }) </script> ``` ## 个人中心其他信息修改 ### 个人信息模板表单 ```html <form class="form-horizontal" id="js_user_info_form"> <div class="promo"> <div class="form-group"> <label class="col-sm-2 control-label">昵&nbsp;&nbsp;&nbsp;&nbsp;称</label> <div class="col-sm-10"> <input type="text" class="form-control" name='nick_name' value="{{ user.nick_name|default_if_none:'' }}"> <div style="color: white; background: red" id="nick_name_error"></div> </div> </div> <div class="hr-line-dashed"></div> <div class="form-group"> <label class="col-sm-2 control-label">生&nbsp;&nbsp;&nbsp;&nbsp;日</label> <div class="col-sm-10"> <input type="text" class="form-control" name="birthday" value="{{ user.birthday|date:'Y-m-d'|default_if_none:'' }}" placeholder="2018-08-08"> <div style="color: white; background: red" id="birthday_error"></div> </div> </div> <div class="hr-line-dashed"></div> <div class="form-group"> <label class="col-sm-2 control-label">性&nbsp;&nbsp;&nbsp;&nbsp;别</label> <div class="col-sm-10"> <select class="form-control" name="gender"> <option value="male" {% ifequal user.gender 'male' %} selected {% endifequal %}>男</option> <option value="female" {% ifequal user.gender 'female' %} selected {% endifequal %}>女</option> </select> </div> </div> <div class="hr-line-dashed"></div> <div class="form-group"> <label class="col-sm-2 control-label">住&nbsp;&nbsp;&nbsp;&nbsp;址</label> <div class="col-sm-10"> <input type="text" class="form-control" required name="address" value="{{ user.address|default_if_none:'' }}"> <div style="color: white; background: red" id="address_error"></div> </div> </div> <div class="hr-line-dashed"></div> <div class="form-group"> <label class="col-sm-2 control-label">手机号</label> <div class="col-sm-10"> <input type="text" class="form-control" name="mobile" required value="{{ user.mobile|default_if_none:'' }}"> <div style="color: white; background: red" id="mobile_error"></div> </div> </div> <div class="hr-line-dashed"></div> <div class="form-group"> <label class="col-sm-2 control-label">邮&nbsp;&nbsp;&nbsp;&nbsp;箱</label> <div class="col-sm-8"> <input type="text" disabled="" name="email" value="{{ user.email }}" class="form-control"> </div> <div class="col-sm-2 control-label"> <a href="#" data-toggle="modal" data-target="#modifyEmailModal"><b>[ 修改 ]</b></a> </div> </div> <div class="form-group"> <div class="col-sm-6 col-md-offset-2" id="usercenter_msg"></div> </div> </div> {% csrf_token %} <!-- Button --> <div class="pro-btn"> <button class="btn-round" type="button" id="js_user_info_button">保存修改</button> </div> </form> ``` ![BLOG_20190604_141900_43](/media/blog/images/2019/06/BLOG_20190604_141900_43.png "博客图集BLOG_20190604_141900_43.png") ### 个人信息js提交及错误显示 ```html <script type="text/javascript"> //提交用户信息修改 $(function () { $('#js_user_info_button').on('click', function () { $.ajax({ cache: false, type: 'POST', url: '{% url "users:user_info" %}', data: $('#js_user_info_form').serialize(), async: true, success: function (data) { if (data.info_save_status === 'success') { $('#usercenter_msg').html(data.info_save__msg); setTimeout( 'window.location.reload()', 1000 ); } else { $('#nick_name_error').html(data.nick_name); $('#birthday_error').html(data.birthday); $('#address_error').html(data.address); $('#mobile_error').html(data.mobile); } }, }); }); }) </script> ``` ### 个人信息模型表单 ```python # 个人信息修改表单 class UserCenterInfoForm(forms.ModelForm): class Meta: model = UserProfile fields = ('nick_name', 'gender', 'birthday', 'address', 'mobile') ``` ### 个人信息post视图 ```python # 用户中心个人信息 class UserCenterInfoView(LoginRequiredMixin, View): login_url = '/login/' redirect_field_name = 'next' def get(self, request): return render(request, 'usercenter-info.html', locals()) def post(self, request): user_center_info_form = UserCenterInfoForm(request.POST, instance=request.user) # 传递一个user实例,否则是新增,而不是修改 if user_center_info_form.is_valid(): user_center_info_form.save() return HttpResponse('{"info_save_status":"success", "info_save__msg":"用户信息更新成功"}', content_type='application/json') else: user_center_info_errors = json.dumps(user_center_info_form.errors, ensure_ascii=False) print(user_center_info_errors) return HttpResponse(user_center_info_errors, content_type='application/json') ```

很赞哦! (1)

文章交流

  • emoji
0人参与,0条评论

当前用户

未登录,点击   登录

站点信息

  • 建站时间:网站已运行657天
  • 系统信息:Linux
  • 后台程序:Python: 3.6.6
  • 网站框架:Django: 2.2.12
  • 文章统计:235 篇
  • 文章评论:40 条
  • 腾讯分析网站概况-腾讯分析
  • 百度统计网站概况-百度统计
  • 公众号:微信扫描二维码,关注我们
  • QQ群:QQ加群,下载网站的学习源码
返回
顶部
标题 换行 登录
网站