• 29、Django实战第29天:修改密码和头像


    修改头像

    1、上传头像,我们需要的对它做一个forms验证,编辑users.forms.py

    ...
    from .models import UserProfile
    
    
    class UploadImageForm(forms.ModelForm):
        class Meta:
            model = UserProfile
            fields = ['image']

    2、编辑users.views.py

    class UploadImageView(LoginRequiredMixin, View):
        def post(self, request):
            image_form = UploadImageForm(request.POST, request.FILES)
            if image_form.is_valid():
                pass
    

    3、配置url,编辑users.urls.py

    ...
    from .views import UploadImageView
    
    urlpatterns = [
        ...
        url(r'image/upload/$', UploadImageView.as_view(), name='upload_image'),
    ]

    4、编辑前端页面

    5、断点调试

    我们发现form已经取到上传的图片放到了cleaned_data中,这里面的数据是已经通过验证的。因此我们可以直接把它取出来保存到数据库中

    因为我们用的是mode.form,所以我们可以直接保存到数据库,优化代码如下:

    最后我们需要返回一个json 信息,因为,这里修改头像是个异步的操作

    ...
    from django.http import HttpResponse
    
    
    class UploadImageView(LoginRequiredMixin, View):
        def post(self, request):
            image_form = UploadImageForm(request.POST, request.FILES, instance=request.user)
            if image_form.is_valid():
                image_form.save()
                return HttpResponse('{"status":"success"}', content_type='application/json')
            else:
                return HttpResponse('{"status":"fail"}', content_type='application/json')
    

      

     修改密码

    编辑users.views.py

    ...
    import json
    
    class UpdatePwdView(LoginRequiredMixin, View):
        def post(self, request):
            ResetPwd_form = ResetPwdForm(request.POST)
            if ResetPwd_form.is_valid():
                pwd = request.POST.get('pwd', '')
                repwd = request.POST.get('repwd', '')
                if pwd == repwd:
                    user = UserProfile.objects.get(email=request.user.email)
                    user.password = make_password(pwd)
                    user.save()
                    return HttpResponse('{"status":"success"}', content_type='application/json')
                else:
                    return HttpResponse('{"status":"fail", "msg":"密码不一致"}', content_type='application/json')
            else:
                return HttpResponse(json.dumps(ResetPwd_form.errors), content_type='application/json')

    配置url,编辑users.urls.py

    ...
    from .views import  UpdatePwdView
    
    urlpatterns = [
        ...
        url(r'update/pwd/$', UpdatePwdView.as_view(), name='update_pwd'),
    ]
    

    编辑前端页面usercenter-base.html

    提交地址配置在deco-user.js中

  • 相关阅读:
    RabbitMQ 部署记录
    Linux下安装db2
    CentOS7 安装 Redis 并设置开机启动
    Firewalld 使用指南
    centos7 redis安装教程
    Centos7下杀毒软件clamav的安装和使用
    centos7 zookeeper集群搭建
    centos开机执行JAR Shell脚本
    centos7 防火墙常用设置
    centos7 Systemd 指令详解
  • 原文地址:https://www.cnblogs.com/sellsa/p/8656279.html
Copyright © 2020-2023  润新知