修改密码和头像10-4

1.view书写
class UploadImageView(LoginRequiredMixin, View):
“”"
用户修改头像
“”"

方法1
def post(self, request):

    image_form = UploadImageForm(request.POST, request.FILES)
    if image_form.is_valid():
        image = image_form.cleaned_data['image']
        request.user.image = image
        request.user.save()
       return HttpResponse('{"status":"success"}', content_type='application/json')
    else:
        return HttpResponse('{"status":"fail"}', content_type='application/json')

// request.FILES上传文件需要配置的
//image_form.cleaned_data[‘image’],form会将验证通过的字段放在里面
方法2
运用ModelForm的性质

  • 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')
    

2.form表单定义

class UploadImageForm(forms.ModelForm):

class Meta:
    model = UserProfile
    fields = ['image']   

3. html修改
4. 添加url

url(r’^image/upload/$’, UploadImageView.as_view(), name=‘image_upload’),

你可能感兴趣的:(django)