Django-request对象

request对象

当一个页面被请求时,django就会创建一个包含本次请求原信息的HttpResquest对象,django会将这个对象自动传递给相应的视图函数,约定俗成,由request参数来接收这个对象。

常用值 属性 常用值 属性
.path_info 返回用户访问url,不包括域名 .GET 包含所有HTTP GET参数的类字典对象
.method 请求中使用的HTTP方法的字符串表示,
全大写表示。
.POST 包含所有HTTP POST参数的类字典对象
.body 请求体,byte类型 request.POST的数据
就是从body里面提取到的
.COOKIES 包含了所有cookies的字典
.session 可读又可写的字典对象,表示当前的会话 .FILES 包含了所有的上传文件的querydict对象
.is_ajax() 判断是否是ajax请求 .META 包含了所有http头部信息的字典
.get_full_path() 完整的路径信息 不包含IP和端口 包含查询参数

HttpRequest.FILES使用注意事项

1.form表单应设置 enctype="multipart/form-data",将所传数据传输,否则传输的是一个空的类似于字典的对象
2.input的 type = "file",设置multiple可以添加多个文件
3.添加{% csrf_token %}标签,使用request.FILES.get() 接收所传输的文件   

【实例】
# views设置
from django.shortcuts import render, HttpResponse, redirect
from django.views import View
from django.utils.decorators import method_decorator
from app01.templatetages import tags
@method_decorator(tags.wrapper, name="dispatch")

class Upload(View):

    def get(self, request):
        return render(request, "upload.html")

    def post(self, request):
        obj = request.FILES.get("f1")
        with open(obj.name, mode="wb") as f:
            for line in obj.chunks():
                f.write(line)
        return HttpResponse("succeed")
------------------------------------------------------------------------------------------------- 
# HTML设置
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
  <div >
    <label for="InputFile">选择上传的文件</label>
    <input type="file" id="InputFile" name="f1">
    <p class="help-block">Example block-level help text here.</p>
  </div>
  <button type="submit" class="btn btn-default">Submit</button>
</form>    
原文地址:https://www.cnblogs.com/jjzz1234/p/11619806.html