29、Django实战第29天:修改密码和头像
修改头像
1、上传头像,我们需要的对它做一个forms验证,编辑users.forms.py
1 2 3 4 5 6 7 8 | ... from .models import UserProfile class UploadImageForm(forms.ModelForm): class Meta: model = UserProfile fields = [ 'image' ] |
2、编辑users.views.py
1 2 3 4 5 | 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
1 2 3 4 5 6 7 | ... from .views import UploadImageView urlpatterns = [ ... url(r 'image/upload/$' , UploadImageView.as_view(), name = 'upload_image' ), ] |
4、编辑前端页面
5、断点调试
我们发现form已经取到上传的图片放到了cleaned_data中,这里面的数据是已经通过验证的。因此我们可以直接把它取出来保存到数据库中
因为我们用的是mode.form,所以我们可以直接保存到数据库,优化代码如下:
最后我们需要返回一个json 信息,因为,这里修改头像是个异步的操作
1 2 3 4 5 6 7 8 9 10 11 12 | ... 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | ... 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
1 2 3 4 5 6 7 | ... from .views import UpdatePwdView urlpatterns = [ ... url(r 'update/pwd/$' , UpdatePwdView.as_view(), name = 'update_pwd' ), ] |
编辑前端页面usercenter-base.html
提交地址配置在deco-user.js中
每天进步一点,加油!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步