Form组件之上传
Form组件之上传
from django.shortcuts import render,redirect,HttpResponse from django.forms import Form from django.forms import fields from django.forms import widgets from app01 import models import os class F2Form(Form): user = fields.CharField() fafafa = fields.FileField() def f1(request): if request.method=="GET": return render(request,'f1.html') else: print(request.FILES) file_obj = request.FILES.get("fafafa") f = open(os.path.join('static',file_obj.name),'wb') for chunk in file_obj.chunks(): f.write(chunk) f.close() return render(request,'f1.html') def f2(request): if request.method == "GET": obj = F2Form() return render(request,'f2.html',{'obj':obj}) else: obj = F2Form(data=request.POST,files=request.FILES) if obj.is_valid(): print(obj.cleaned_data.get("fafafa").name) print(obj.cleaned_data.get("fafafa").size) return render(request,'f2.html',{'obj':obj})
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="POST" action="/f1/" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="fafafa"> <input type="submit" value="提交"> </form> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="POST" action="/f2/" enctype="multipart/form-data"> {% csrf_token %} {{ obj.user }} {{ obj.fafafa }} <input type="submit" value="提交"> </form> </body> </html>