python django中简单获取提交表单数据和将上传的文件保存
html
<form action="/login/" 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"/> </p> <p> 男:<input type="checkbox" name="favor" value="11"/> 女:<input type="checkbox" name="favor" value="22"/> </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"/> </p> <input type="submit" value="提交"/> </form>
views
def login(request): if request.method == "GET": return render(request, 'login.html') elif request.method == "POST": # radio # v = request.POST.get('gender') # print(v) # v = request.POST.getlist('favor') # print(v) # v = request.POST.get('fafafa') # print(v) obj = request.FILES.get('fafafa') print(obj,type(obj),obj.name) import os file_path = os.path.join('upload', obj.name) f = open(file_path, mode="wb") for i in obj.chunks(): f.write(i) f.close() return render(request, 'login.html') else: # PUT,DELETE,HEAD,OPTION... return redirect('/index/')