Django之序列化类的使用、form表单上传文件、其它request方法、CBV的写法

【1】序列化类的使用

【1.1】Django项目中如何使用序列化
python 复制代码
# 第一步:导入方法

from django.http import JsonResponse

# 第二步,使用

# 2.1 定义一个需要序列化的数据

  def index(request):
    user_dict = {'username':'jack','age':18}

    # 序列化

    return JsonResponse(user_dict)
 
'''
注意事项:
    在序列化一个不是字典的数据时,在序列化的时候需要给JsonResponse中的safe这个参数的值改为False

'''

def index(request):
    user_list = [1,2,3,4,5]

    # 序列化

    return JsonResponse(user_list,safe=False)

【2】form表单上传文件

【2.1】form表单上传文件需要满足的条件
  • 请求方式必须是post(method=' post ')
  • 编码类型必须是multipart/form-data(enctype="multipart/form-data")
  • 【2.2】后端接收文件使用的方法
    • request.FILES
      • 接收文件数据
    • request.FILES.get('file')
      • 获取文件对象

【3】其它request方法

  • request.FILES
    • 接收form表单传过来的文件数据
  • reqeust.FILES.get('')
    • 获取文件对象
  • reqeust.path
    • 获取网址栏上的地址,不能获得参数
  • request.path_info
    • 获取网址栏上的地址,不能获得参数
  • reqeust.get_full_path()
    • 不仅能获取网址栏上的地址,还能获取网址栏上的参数

【4】CBV的写法

FBV:function based view ---------- 写的都是函数

CBV:class based view ------------ 写的都是类

python 复制代码
views.py文件:

from django.view import View


class MyLogin(View):
    def get(self,request):
        return HttpResponse("get")

    def post(self, request):
        return HttpResponse("hello postman")




urls.py文件:
    
    url(r'^login/',view.MyLogin.as_view())

CBV中类中的函数名只能写以下列表中的,其余的不能写。

http_method_names = 'get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'

相关推荐
zmzb0103几秒前
Python课后习题训练记录Day123
开发语言·python
PersistJiao2 分钟前
python环境下免费、专业的中英翻译
开发语言·windows·python·机器翻译
Gopher_HBo5 分钟前
存储技术Redis
后端
hujinyuan2016017 分钟前
中国电子学会青少年软件编程(Python)(二级)等级考试试卷-真题+答案(2026年3月)
python·机器人
xindon1219 分钟前
go语言项目部署的makefile
开发语言·后端·golang
老毛肚20 分钟前
记一次逆向
开发语言·python
星恒随风34 分钟前
Python 基础语法详解(3):顺序语句、条件语句和循环语句一篇讲清楚
开发语言·笔记·python·学习
凤头百灵鸟35 分钟前
Python语法进阶篇 --- re库、os库、sys库、time库、logging库、random库
python
276695829242 分钟前
jd 变速滑块逆向角度分析
前端·python·京东滑块·京东逆向·京东变速滑块·cfe滑块·wasm逆向