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

【Django在线教育平台】17.个人中心用户修改密码、头像

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

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

## 个人中心url 在users应用下创建urls.py文件 ```python from django.urls import path, re_path app_name = 'users' urlpatterns = [ # 用户相关url ] ``` 然后再主url中添加 ```python path('usercenter/', include('users.urls', namespace='usercenter')), ``` ## 个人中心视图 users/views/py ```python from django.contrib.auth.mixins import LoginRequiredMixin # 需要登录才能访问 # 用户中心个人信息 class UserCenterInfoView(LoginRequiredMixin, View): login_url = '/login/' redirect_field_name = 'next' def get(self, request): return render(request, 'usercenter-info.html', locals()) ``` ## 个人中心修改密码 ### 修改密码模态框表单 ```html <div class="pro-btn"><a href="" class="btn-round btn-light" data-toggle="modal" data-target="#modifyPasswordModal">修改密码</a></div> <div class="modal fade padding-top-150" id="modifyPasswordModal" tabindex="-1" role="dialog" aria-labelledby="modifyPasswordModalLabel" 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="myModalLabel"> 密码修改 &nbsp;&nbsp; <small id="modify_msg" style="color: red"></small> </h5> </div> <div class="modal-body"> <form method="get" class="form-horizontal"> <div class="form-group"> <label class="col-sm-2 control-label">新密码</label> <div class="col-sm-10" style="width: 80%"> <input type="password" class="form-control" id="password" name='password' value=""> </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" style="width: 80%"> <input type="password" class="form-control" id="re_password" name='re_password' value=""> </div> </div> </form> </div> <div class="modal-footer"> <div class="pro-btn"> <button type="button" class="btn-round btn-light" data-dismiss="modal">关闭 </button> <button type="button" class="btn-round" id="modify_pwd_modal"> 提交更改 </button> </div> </div> </div><!-- /.modal-content --> </div><!-- /.modal --> </div> <script type="text/javascript"> $('#modify_pwd_modal').on('click', function () { let password = $('#password').val(); let re_password = $('#re_password').val(); $.ajax({ cache: false, type: "POST", url: "{% url 'usercenter:user_modify_pwd' %}", data: {'password': password, 're_password': re_password}, async: true, beforeSend: function (xhr, settings) { xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}"); }, success: function (data) { if (data.modify_status === 'fail') { //alert(data.modify_msg); $('#modify_msg').html(data.modify_msg); } else if (data.modify_status === 'success') { $('#modify_msg').html(data.modify_msg); } }, }); }) </script> ``` ![BLOG_20190604_141757_90](/media/blog/images/2019/06/BLOG_20190604_141757_90.png "博客图集BLOG_20190604_141757_90.png") ### 修改密码视图 该视图使用之前创建的`ModifyPwdForm(forms.Form)`表单,用于重置密码修改的 ```python # 用户修改密码 class UserModifypwdView(LoginRequiredMixin, View): login_url = '/login/' redirect_field_name = 'next' def post(self, request): modifypwd_form = ModifyPwdForm(request.POST) if modifypwd_form.is_valid(): pwd1 = request.POST.get("password", "") pwd2 = request.POST.get("re_password", "") # 如果两次密码不相等,返回错误信息 if pwd1 != pwd2: return HttpResponse('{"modify_status":"fail", "modify_msg":"两次密码不一致"}', content_type='application/json') # 如果密码一致 user = request.user # 加密成密文 user.password = make_password(pwd2) # save保存到数据库 user.save() return HttpResponse('{"modify_status":"success", "modify_msg":"密码修改成功"}', content_type='application/json') else: return HttpResponse('{"modify_status":"fail", "modify_msg":"密码不符合要求"}', content_type='application/json') ``` ### 修改密码url ```python from .views import UserCenterInfoView, UserModifypwdView app_name = 'users' urlpatterns = [ # 用户相关url path('info/', UserCenterInfoView.as_view(), name='user_info'), # 用户信息 path('password/modify/', UserModifypwdView.as_view(), name='user_modify_pwd'), # 修改密码 ] ``` ## 个人中心修改头像 ### 修改头像模态框 ```html <img class="img-responsive" src="{{ user.image.url }}" alt=""> <div class="pro-btn"><a href="" class="btn-round btn-light" data-toggle="modal" data-target="#modifyImageModal">修改头像</a></div> <div class="modal fade padding-top-150" id="modifyImageModal" tabindex="-1" role="dialog" aria-labelledby="modifyImageModalLabel" 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="myModalLabel"> 头像修改 &nbsp; <small id="upload_msg" style="color: red">选择文件后自动上传修改</small> </h5> </div> <div class="modal-body"> <div class="row"> <div class="col-md-4"> <img class="img-responsive" src="{{ user.image.url }}" alt=""> </div> <div class="col-md-4" style="text-align: center; vertical-align: middle;"> <input name="image" type="file" onchange="upload_image()" id="choose_image"> <br><br> ========修改为======> </div> <div class="col-md-4"> <img class="img-responsive" src="{{ user.image.url }}" alt="" id="show_image"> </div> </div> </div> <div class="modal-footer"> <div class="pro-btn"> <button type="button" class="btn-round btn-light" data-dismiss="modal" onclick="javascript:location.reload();">关闭 <!-- 点击关闭自动刷新页面 --> </button> </div> </div> </div><!-- /.modal-content --> </div><!-- /.modal --> </div> ``` ![BLOG_20190604_141748_63](/media/blog/images/2019/06/BLOG_20190604_141748_63.png "博客图集BLOG_20190604_141748_63.png") ### 修改头像js自动上传 ```html <script type="text/javascript"> //上传图片 function upload_image() { let formData = new FormData(); //let image_file = document.getElementById('choose_image').files[0]; //alert(image_file); formData.append('image', $('#choose_image')[0].files[0]); $.ajax({ cache: false, type: "POST", url: "{% url 'usercenter:user_image_upload' %}", data: formData, // 告诉jQuery不要去处理发送的数据 processData: false, // 告诉jQuery不要去设置Content-Type请求头 contentType: false, mimeType: "multipart/form-data", dataType: "json", async: true, beforeSend: function (xhr, settings) { xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}"); }, success: function (data) { $('#upload_msg').html(data.upload_msg); if (data.upload_status === 'fail') { //alert(data.upload_msg); //$('#upload_msg').html(data.upload_msg); } else if (data.upload_status === 'success') { //alert(data.image_url); document.getElementById('show_image').src = data.image_url; } }, }); } </script> ``` ### 修改头像表单 ```python # 用户头像上传表单 class UserImageUploadForm(forms.ModelForm): class Meta: model = UserProfile fields = ('image', ) @staticmethod def valid_image(image_name): """ 验证图片后缀 """ image_regex = r'.*(.jpg|.png|.gif)$' cp = re.compile(image_regex) if not cp.match(image_name.lower()): # print('图片验证不通过') return False return True def clean_image(self): image = self.cleaned_data['image'] # print(image) if not image or self.valid_image(image.name) is False: raise forms.ValidationError('请选择jpg、png或gif格式的图片') return image ``` ### 修改头像视图,自动删除原头像 ```python # 用户上传图片 class UserImageUploadView(LoginRequiredMixin, View): login_url = '/login/' redirect_field_name = 'next' def post(self, request): print('即将上传图片') # 这时候用户上传的文件就已经被保存到image_upload_form了 ,为modelform添加instance值直接保存 image_upload_form = UserImageUploadForm(request.POST, request.FILES) if image_upload_form.is_valid(): # 对原头像进行删除 base_dir = settings.BASE_DIR # print(base_dir) user_image_path = request.user.image.path # print(user_image_path) user_absolute_path = os.path.join(base_dir, user_image_path) print(user_absolute_path) if os.path.exists(user_absolute_path): # print('头像存在,正在删除') os.remove(user_absolute_path) # 上传新头像保存 # print(image_upload_form.cleaned_data['image']) image = image_upload_form.cleaned_data['image'] request.user.image = image request.user.save() return HttpResponse('{"upload_status":"success", "upload_msg":"头像上传成功,自动修改头像", "image_url": "' + request.user.image.url + '"}', content_type='application/json') else: print('图片上传失败', image_upload_form.errors) return HttpResponse('{"upload_status":"fail", "upload_msg":"头像上传失败"}', content_type='application/json') ``` ### 修改头像url ```python from .views import UserCenterInfoView, UserModifypwdView, UserImageUploadView 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'), # 用户上传头像 ] ```

很赞哦! (1)

文章交流

  • emoji
0人参与,0条评论

当前用户

未登录,点击   登录

站点信息

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