注册页面的头像上传 register.html
<!DOCTYPE html>
 1 <html lang="en">
 2 <head>
 3     <meta charset="UTF-8">
 4     <title>Title</title>
 5 </head>
 6 <body>
 7     <div style="margin-left: 30px; margin-top: 30px">
 8         <form action="">
 9             {% csrf_token %}
10         <h3>用户注册</h3>
11         <p>用户名:<input type="text" name="user"></p>
12         <p>密 码 :<input type="password" name="pwd"></p>
13         <p>再输入:<input type="password" name="pwd"></p>
14         <p>昵 称 :<input type="text" name="nickname"></p>
15         <p>邮 箱 :<input type="text" name="email"></p>
16             <input id="avatar" type="file" value="上传头像"> {# 实际应用中要将该input标签隐藏,display:none; #}
17             <p><input type="submit" value="注册" style="margin-left:50px;width:100px;"></p>
18         </form>
19         <div style="position: absolute; top: 85px; left: 300px;">
20         <input id="avatarSelect" type="file" style="position: absolute;float: left; z-index: 10; opacity: 0;width: 100px; height: 100px;">
21         <img id="avatarPreview" src="/static/img/default.png" title="点击更换图片" style="position: absolute; z-index: 9; float: left; width: 100px; height: 100px">
22             </div>
23     </div>
24 </body>
25 
26 <script src="\static\jquery-3.3.1.min.js"></script>
27 <script>
28     $(function () {
29             bindAvatar();
30     });
31 
32     function bindAvatar() {
33             if(window.URL.createObjectURL){
34                 bindAvatar3();
35             }else if(window.FileReader){
36                 bindAvatar2();
37             }else {
38                 bindAvatar1();
39             }
40     }
41 
42     /*Ajax上传至后台并返回图片的url*/
43     function bindAvatar1() {
44         $("#avatarSelect").change(function () {
45         var csrf = $("input[name='csrfmiddlewaretoken']").val();
46         var formData=new FormData();
47         formData.append("csrfmiddlewaretoken",csrf);
48         formData.append('avatar', $("#avatarSelect")[0].files[0]);
49         console.log(formData);
50             /*获取上传的图片对象*/
51         $.ajax({
52             url: '/avatar_load/',
53                     type: 'POST',
54                     data: formData,
55                     contentType: false,
56                     processData: false,
57                     success: function (args) {
58                     console.log('年后哦')
59                     console.log(args);              /*服务器端的图片地址*/
60                     $("#avatarPreview").attr('src','/'+args);        /*预览图片*/
61                     $("#avatar").val('/'+args);     /*将服务端的图片url赋值给form表单的隐藏input标签*/
62                     }
63             })
64         })
65     }
66     /*window.FileReader本地预览*/
67     function bindAvatar2() {
68         console.log(2);
69              $("#avatarSelect").change(function () {
70                      var obj=$("#avatarSelect")[0].files[0];
71                      var fr=new FileReader();
72                      fr.readAsDataURL(obj);
73                      fr.onload=function () {
74                              $("#avatarPreview").attr('src',this.result);
75                              console.log(this.result);
76                              $("#avatar").val(this.result);
77            };
78            fr.readAsDataURL(obj);
79        })
80   }
81   /*window.URL.createObjectURL本地预览*/
82   function bindAvatar3() {
83       console.log(3);
84             $("#avatarSelect").change(function () {
85                     var obj=$("#avatarSelect")[0].files[0];
86                     var wuc=window.URL.createObjectURL(obj);
87                      $("#avatarPreview").attr('src',wuc);
88                      $("#avatar").val(wuc);
89 {#                     $("#avatarPreview").load(function () {#}        /*当图片加载后释放内存空间,但在jQuery3.2.1中会报错。浏览器关闭后也会自动释放*/
90 {#                             window.URL.revokeObjectURL(wuc);#}
91 {#           })#}
92       })
93   }
94 
95 </script>
96 </html>


视图函数 


 1 def register(request):
 2     """注册
 3     :param request
 4     :return"""
 5     if request.method == 'GET':
 6         return render(request,'register.html')
 7 
 8 def avatar_reg(request):
 9     """
10     :param request: (avatar头像对象)
11     :return:
12     """
13     file_obj = request.FILES.get('avatar')
14     file_path = os.path.join('static/img',file_obj.name)
15     with open(file_path,'wb') as f:
16         for chunk in file_obj.chunks():
17             f.write(chunk)
18     print file_path
19     return HttpResponse(file_path)

 

 

路由系统 url.py

 1 from django.conf.urls import url
 2 from django.contrib import admin
 3 from app_boke import views
 4 urlpatterns = [
 5     url(r'^admin/', admin.site.urls),
 6     url(r'^all/(?P<url_id>\d+)/', views.test),#正则p是大写,页面的参数和type_id组成键值对穿个函数中的变量kwargs
 7     url(r'^$', views.test), #默认输入域名或ip到达首页,上下兼容,必须加斜杠或者终止符不然可能跟其他的url有路径冲突(这种匹配追号写到地下,匹配是从上往下)
 8     url(r'^login/', views.login),
 9     url(r'^ajax_login/', views.ajax_login),
10     url(r'^login1/', views.login1),
11     url(r'^index/', views.index),
12     url(r'^check_code/', views.check_code),
13     url(r'^register/', views.register),
14     url(r'^avatar_load/', views.avatar_reg),
15 ]

Form表单组件出现的错误信息

{
    __all__:[错误1,错误2], 整体共有的错误
    user:[错误1,错误2],
    password:[错误1,错误2],
}  
#获取整体。共有错误信息  
-后台 对象的errors属性
    print(obj.errors['__all__'])或者  #参考源码
    print(obj.errors['NON_FIELD_ERRORS'])
-模板(前端)
    {{obj,non_filed_errors}}  特殊