JsonResponse方法
首先,如果不使用JsonResponse如何给前端返回json格式字符串
def index_func (request ):
user_list = {'name' : '汤姆' , 'age' : 8 }
json_list = json.dumps(user_list, ensure_ascii=False )
return HttpResponse(json_list)
使用JsonResponse给前端返回json格式字符串
from django.http import JsonResponse
def index_func (request ):
user_list = {'name' : '汤姆' , 'age' : 8 }
return JsonResponse(user_list)
def __init__ (self, data, encoder=DjangoJSONEncoder, safe=True ,
json_dumps_params=None , **kwargs ):
if safe and not isinstance (data, dict ):
raise TypeError(
'In order to allow non-dict objects to be serialized set the '
'safe parameter to False.'
)
if json_dumps_params is None :
json_dumps_params = {}
kwargs.setdefault('content_type' , 'application/json' )
'''
分析2:如果要传中文,命令应该为json_list = json.dumps(user_list, ensure_ascii=False)
转换为源码中的命令则为:data = json.dumps(data, cls=encoder, ensure_ascii=False)
'''
data = json.dumps(data, cls=encoder, **json_dumps_params)
super ().__init__(content=data, **kwargs)
所以传输中文方法为使用json_dumps_params={'ensure_ascii': False}参数
from django.http import JsonResponse
def index_func (request ):
user_list = {'name' : '汤姆' , 'age' : 8 }
return JsonResponse(user_list, json_dumps_params={'ensure_ascii' : False })
序列化列表
from django.http import JsonResponse
def index_func (request ):
user_list = [1 , 2 , 3 , 4 , 5 , 6 ]
return JsonResponse(user_list, json_dumps_params={'ensure_ascii' : False }, safe=False )
request对象获取文件
上传单个文件
form表单中如果要上传文件,需要在前端form表单定义参数。
前端定义参数
method="post"
enctype="multipart/form-data" # 默认为enctype="application/x-www-form-urlencoded"
request.FILES
<body >
<div class ="container" >
<form action ="" class ="form-control" method ="post" enctype ="multipart/form-data" >
{% csrf_token %}
<p > 用户名
<input type ="text" name ="username" >
</p >
<p > 密码
<input type ="password" name ="password" >
</p >
<p > hoppy:
<input type ="checkbox" name ="hobby" value ="basketball" > 篮球
<input type ="checkbox" name ="hobby" value ="football" > 足球
<input type ="checkbox" name ="hobby" value ="icehockey" > 冰球
</p >
<p > file
<input type ="file" name ="file" >
</p >
<button > 提交</button >
</form >
</div >
<div align ="center" > </div >
</body >
def index_func (request ):
if request.method == 'POST' :
username = request.POST.get('username' )
password = request.POST.get('password' )
checkbox = request.POST.getlist('hobby' )
print ('username>>>:' , username)
print ('password>>>:' , password)
print ('checkbox>>>:' , checkbox)
return render(request, 'test1.html' )
return render(request, 'test1.html' )
def index_func (request ):
if request.method == 'POST' :
file_obj = request.FILES.get('file' )
with open (file_obj.name, 'wb' ) as f:
for line in file_obj:
f.write(line)
return render(request, 'test1.html' )
return render(request, 'test1.html' )
上传多个文件
<input type ="file" name ="file" multiple > # input表单中添加multiple参数
request.FILES.getlist(file)
将文件保存在本地
def index_func (request ):
if request.method == 'POST' :
for file_obj in request.FILES.getlist('file' ):
with open (f'%s' % file_obj.name, 'wb' ) as f:
for line in file_obj:
f.write(line)
return render(request, 'test1.html' )
return render(request, 'test1.html' )
FBV与CBV
FBV (function based view) 基于函数的视图
def myFunction (request ):
return HttpResponse('Hello World' )
CBV (class based view) 基于类的视图
from django import views
class MyCBVTest (views.View):
def get (self, request ):
return render(request, 'login.html' )
def post (self, request ):
return HttpResponse('I am CBV Post method!' )
path('login/' , views.MyCBVTest.as_view()),
<body >
<p > I am CBV get method</p >
<form action ="/login/" method ="post" >
{% csrf_token %}
<input type ="submit" > 点我
</form >
</body >
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类