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})
views.py
<!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>
f1.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>
f2.html

 

posted @ 2017-07-05 16:24  luchuangao  阅读(86)  评论(0编辑  收藏  举报