上传的功能怎么实现:
前面注册页面: <body> <div class="container"> <div class="row"> <form class="col-md-6 col-md-offset-2"> {% csrf_token %} <div class="form-group"> <label for="user">用户名</label> {{ regForm.username }} <span class="error"></span> </div> <div class="form-group"> <label for="pwd">密码</label> {{ regForm.password }} <span class="error"></span> </div> <div class="form-group"> <label for="pwd">确认密码</label> {{ regForm.repeat_password }} <span class="error"></span> </div> <div class="form-group"> <label for="pwd">邮箱</label> {{ regForm.email }} <span class="error"></span> </div> <div class="form-group" id="avatar"> <label for="pwd">头像</label> <p><img src="/static/img/default.png" alt="" id="avatar_img"></p> <p><input type="file" id="file"></p> </div> <div class="row"> <div class="col-md-6"> <input type="button"value="注册提交" class="btn btn-primary regBtn"><span class="error"></span> </div> </div> </form> </div> </div> <script> $(".regBtn").click(function () { var formdata=new FormData(); formdata.append("username",$("#id_username").val()); formdata.append("password",$("#id_password").val()); formdata.append("repeat_password",$("#id_repeat_password").val()); formdata.append("email",$("#id_email").val()); formdata.append("csrfmiddlewaretoken",$("[name=‘csrfmiddlewaretoken‘]").val()); formdata.append("avatar",$("#file")[0].files[0]); $.ajax({ url:"/reg/", type:"post", data:formdata, contentType:false, processData:false, success:function (data) { var data=JSON.parse(data); //console.log(data); if(data.user){ location.href="/login/" } else { var error_dict=data.error_msg ; // {"username":["asda"],"email":["asdsa"]} $(".error").html(""); $.each(error_dict,function (i,j) { console.log(i,j); $("#id_"+i).next().addClass("pull-right").html(j[0]).css("color","red") if(i=="__all__"){ $("#id_repeat_password").next().html(j[0]) } }) } } }) }) // 预览功能 $("#file").change(function () { var choose_file=$("#file")[0].files[0]; var reader=new FileReader(); reader.readAsDataURL(choose_file); reader.onload=function () { $("#avatar_img").attr("src",this.result) } }) </script>
后台views怎么写的: def reg(request): if request.is_ajax(): regForm=RegForm(request.POST) regResponse={"user":None,"error_msg":None} if regForm.is_valid(): username=regForm.cleaned_data.get("username") password=regForm.cleaned_data.get("password") email=regForm.cleaned_data.get("email") avatar=request.FILES.get("avatar") print(regForm.cleaned_data,"------") user=UserInfo.objects.create_user(username=username,password=password,email=email,avatar=avatar) regResponse["user"]=user.username else: regResponse["error_msg"]=regForm.errors # errors只存错误字段 return HttpResponse(json.dumps(regResponse)) regForm=RegForm() return render(request,‘reg.html‘,locals())