django 文件上传

 

json上传

在学过的请求方式中, 客户端可以接受的请求有 request.post,request.get

实际上,服务端早已将我们的请求方式 比如post 请求 是先按照 & 分组,再按照= 分组

要是将上传json 的形式,服务器需要一个 contype 请求头 告知 服务器按 json 翻译

如:

 1 <h4>2 携带参数的AJax</h4>
 2 {% csrf_token %}
 3 <input type="text" id="num1"> + <input id="num2" type="text"> = <input id="ret" type="text"><button class="cal">计算</button>
 4 <hr>
 5        //  传参Ajax请求
 6        
 7        $(".cal").click(function () {
 8 
 9            var num1=$("#num1").val();
10            var num2=$("#num2").val();
11            {#1.from表单无法传递json 只能通过ajax传递 json在django中至关重要#}
12            $.ajax({
13                url:"/cal/",
14                type:"post",
15                {#2.在传递json中 需要告知服务端你发送的请求,让它按照要求解析,否则无法获取到数值#}
16                contentType:"json",
17                {#3.在传递参数的时候需要将变量序列化#}
18                data:JSON.stringify({
19                    num1:num1,
20                    num2:num2,
21                    //csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']").val()
22 
23                }),
24                success:function (response) {
25                    console.log(response);
26                    $("#ret").val(response)
27                }
28 
29            })
30 
31 
32        });
ajax传递json 数据.html
 1 def cal(request):
 2 
 3 
 4     #1. 这里request.body是将传递的json数据以字节的形式展现出来,因为服务器没有反序列化的工具,这里需要自己解开
 5     print(request.body) # b'num1=12&num2=23'                  b'{"num1":"23","num2":"34"}'
 6     print(request.POST) # <QueryDict: {'num1': ['12'], 'num2': ['23']}>  <QueryDict: {}>
 7     '''
 8     Django解析: 
 9          if contentType:"urlencoded":
10             
11                request.POST=data
12          else:
13                request.POST={}
14     
15     
16     '''
17     # 2.反序列化取出json传递的数据
18     import json
19     json_dict=json.loads(request.body.decode("utf8"))
20     print(json_dict["num1"]) # 213
21 
22 
23     return HttpResponse("OK")
反序列化.views

文件上传

 1 </form>
 2 
 3 
 4 <h4>4 form表单形式的文件上传</h4>
 5 
 6 {#1.在from 表单的文件上传中,需要将在from中引入enctype="multipart/form-data" 才能进行文件的上传   #}
 7 {#2.默认为enctype="application/x-www-form-urlencoded" 可有可无 #}
 8 <form action="/file_put/" method="post" enctype="multipart/form-data">
 9     姓名<input type="text" name="user">
10     文件<input type="file" name="file_obj">
11     <input type="submit">
12 </form>
4 form表单形式的文件上传.html
 1 <div>
 2     姓名<input type="text" id="user">
 3     文件<input type="file" name="file_obj" id="file">
 4     <input type="button" class="filebtn" value="提交">
 5     <p class="msg"></p>
 6 </div>
 7     
 8       // 发送文件
 9       $(".filebtn").click(function () {
10 
11           {#1.这里在ajax是将所有的文件数据放入formdata的参数里,进行data 上传#}
12           var formdata=new FormData();
13           formdata.append("file_obj",$("#file")[0].files[0]);
14           formdata.append("user",$("#user").val());
15 
16           $.ajax({
17               url:"/file_put/",
18               type:"post",
19 
20               // Ajax上传文件必备参数
21               processData: false ,    // 不处理数据
22               contentType: false,    // 不设置内容类型
23 
24               data:formdata,
25               success:function (response) {
26                   console.log(response);
27                   if (response=="OK"){
28                       $(".msg").html("提交成功!")
29                   }
30               }
31           })
32           
33       })
ajax形式上传文件.html
 1 def name(request):
 2 
 3     print(request.POST)
 4     return HttpResponse("OK")
 5 
 6 import os
 7 from s15ajax import settings
 8 
 9 def file_put(request):
10 
11     print(request.POST)
12     print(request.FILES)
13     file_obj=request.FILES.get("file_obj")
14     # 1.文件对象有一个name属性,获取文件名称字符串
15     print(file_obj.name)
16     path=file_obj.name
17     #2.利用setting的模块进行文件拼接路径
18 
19     path=os.path.join(settings.BASE_DIR,"media","img",path)
20     with open(path,"wb") as f:
21         for line in file_obj:
22             f.write(line)
23 
24 
25     return HttpResponse("OK"
文件上传.views

 

二.

关于文件分页 django有自己的方式

1.首先创建一大串数据库

增加表比较老土的方法

1     for i in range(1,101):
2         book=Book.objects.create(title="book_%s"%i,price=i*i,pub_date='1997-10-17',publish_id="1")
3 
4         book.authors.add("1")
5     return HttpResponse("OK")
加数据

2.引入模块

3.

 1 <!DOCTYPE html>
 2 <html lang="zh-CN">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <meta name="viewport" content="width=device-width, initial-scale=1">
 7     <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
 8 <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
 9 </head>
10 <body>
11 {#1.便利出这一页的所有书籍#}
12 <ul>
13     {% for book in current_page %}
14     <li>{{ book.title }} ---- {{ book.price }}</li>
15     {% endfor %}
16 
17 {#</ul>#}
18 <nav aria-label="Page navigation">
19   <ul class="pagination">
20 {#2.若存在上一页,有返回TURE#}
21       {% if current_page.has_previous %}
22 {#3.点击上一页会通过 .previous_page_number的语句直接找到在第几页    #}
23           <li> <a href="?page={{ current_page.previous_page_number }}" aria-label="Previous"><span aria-hidden="true">上一页</span></a></li>
24       {% else %}
25 {#4.若是不存在, class="disabled"表示不可以点击        #}
26            <li class="disabled"><a href="">上一页</a></li>
27       {% endif %}
28 
29 
30 {#5.通过.page_range语句 便利出range的所有标签 实现显示#}
31       {% for num in paginator.page_range %}
32           {% if num == current_page_num %}
33           <li class="active"><a href="?page={{ num }}">{{ num }}</a></li>
34           {% else %}
35            <li><a href="?page={{ num }}">{{ num }}</a></li>
36           {% endif %}
37 
38       {% endfor %}
39 
40 
41     <li>
42 {# 6.下一页同上一页#}
43       <a href="#" aria-label="Next">
44         <span aria-hidden="true">下一页</span>
45       </a>
46     </li>
47   </ul>
48 </nav>
49 </body>
50 </html>
分页.html

 

 1 from django.shortcuts import render
 2 
 3 # Create your views here.
 4 
 5 
 6 from app01.models import Book
 7 from django.core.paginator import Paginator,EmptyPage
 8 def index(request):
 9 
10     '''
11 
12     批量插入数据:
13         # for i in range(100):
14         #     Book.objects.create(title="book_%s"%i,price=i*i)
15 
16 
17         book_list=[]
18 
19         for i in range(100):
20             book=Book(title="book_%s"%i,price=i*i)
21             book_list.append(book)
22 
23         Book.objects.bulk_create(book_list)
24 
25 
26 
27     分页器的使用:
28                 book_list = Book.objects.all()
29                 paginator=Paginator(book_list,8)#以每页8个分页
30 
31                 # print(paginator.count)#总数据
32                 # print(paginator.num_pages)#分页数
33                 # print(paginator.page_range)#range(1,12)
34                 #
35                 # page=paginator.page(5)#第五页分页出的书籍
36                 # for i in page:
37                 #     print(i)
38 
39                 # print(page.has_next())#是否有下一个   TURE
40                 # print(page.has_previous())#是否有上一个  FALSE
41                 # print(page.next_page_number())#下一页的个数  6
42                 # print(page.previous_page_number())#上一页的个数   4
43 
44 
45     '''
46     book_list = Book.objects.all()
47     paginator = Paginator(book_list, 10)#这是一串有好东西的代码
48     try:
49         # 1.接收发来的点击请求,是第几页
50         current_page_num=request.POST.get("page",1)
51         # 2.按照第几页显示的全部类内容,通过遍历显示到主页面
52         current_page=paginator.page(current_page_num)
53     except EmptyPage as e:
54         # 3.如果你选中的page页数不存在,默认返回第一页的数据
55         current_page_num=1
56         current_page = paginator.page(1)
57 
58 
59 
60 
61     return render(request,"index.html",{"current_page":current_page,"paginator":paginator,"current_page_num":int(current_page_num)})
分页.views

 

posted @ 2018-10-30 20:25  逆欢  阅读(193)  评论(0)    收藏  举报