Django里面,通过Html页面提交的数据,可以通过在View里面定义的函数通过request参数获取。简单的说,主要可以分出3种情况。
HTML页面传递来的单个数据, 比如radiobox或者text 可以通过request.POST.get获取
HTML页面传递来多个数据,比如checkbox或者option, 可以通过request.POST.getlist获取
HTML页面上传了一个文件,html端需要表明enctype,表示这是一个文件而不是字符串;后台需要通过request.FILES.get获取这个文件的地址,然后通过chunk分块写入指定的地址
现在来看看实例:
HTML页面
upload.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/upload/" method="POST" enctype="multipart/form-data"> <p> <input type="text" name="user" placeholder="用户名" /> </p> <p> <input type="password" name="pwd" placeholder="密码" /> </p> <p> 性别: 男<input type="radio" name="gender" value="1"/> 女<input type="radio" name="gender" value="2"/> 中<input type="radio" name="gender" value="3"/> </p> <p> 爱好: 音乐<input type="checkbox" name="favor" value="11"/> 武术<input type="checkbox" name="favor" value="22"/> 电玩<input type="checkbox" name="favor" value="33"/> </p> <p> <select name="city" multiple> <option value="sh">上海</option> <option value="bj">北京</option> <option value="tj">天津</option> </select> </p> <p> <input type="file" name="fafafa" enctype="multpart/form-data"/> </p> <input type="submit" value="提交"/> </form> </body> </html>
视图函数
view.py
def upload(request): if request.method == "GET": return render(request, ‘upload.html‘) elif request.method == "POST": v=request.POST.get(‘user‘) print(v) # radio v = request.POST.get(‘gender‘) print(v) v = request.POST.getlist(‘favor‘) print(v) v = request.POST.getlist(‘city‘) print(v) obj = request.FILES.get(‘fafafa‘) print(obj, type(obj), obj.name) import os file_path = os.path.join(‘upload‘, obj.name) print(file_path) f = open(file_path, mode="wb") for i in obj.chunks(): f.write(i) f.close() from django.core.files.uploadedfile import InMemoryUploadedFile return render(request, ‘upload.html‘) else: # PUT,DELETE,HEAD,OPTION... return redirect(‘/upload/‘)
界面
输入下面的值进行提交
成功获取结果
System check identified no issues (0 silenced). July 06, 2017 - 15:25:56 Django version 1.11, using settings ‘Django.settings‘ Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. 阿拉丁 2 [‘22‘, ‘33‘] [‘bj‘, ‘tj‘] statements.pdf <class ‘django.core.files.uploadedfile.InMemoryUploadedFile‘> statements.pdf upload\statements.pdf [06/Jul/2017 15:26:10] "POST /upload/ HTTP/1.1" 200 1267
确认成功上传文件
本文出自 “麻婆豆腐” 博客,请务必保留此出处http://beanxyz.blog.51cto.com/5570417/1944978
原文地址:http://beanxyz.blog.51cto.com/5570417/1944978