2018-10-03-Python全栈开发-day61-DJANGO-上传文件

1.上传文件

  form表单上传

  

def index(request):
    if request.method=='GET':
        obj=Form1()
        return render(request,'index.html',{'obj':obj})
    if request.method=='POST':
        img = request.FILES.get('img')
        f=open(img.name,'wb')
        for i in img.chucks():
            f.write(i)
    
        f.close()
views
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/index" method="post" enctype="multipart/form-data">
{#    {{ obj.username }}#}
{#    {{ obj.email }}#}
    <input type="file" name="img" style="opacity: 0.8;position:absolute;top:0;left: 0;" />
    <input type="submit" value="提交">
</form>
</body>
</html>
html

  制作上传按钮

  步骤:

     将上传按钮和a标签封装到同一个div中,其中将div的position为relative,上传按钮为ablosult,这个时候上传按钮就跑到的div的最左侧,和a标签重叠,其中a标签显示的是另外的样式,这样就变相的实现了这个功能

  基于FORM组件实现上传 fields.File()

  

from django.shortcuts import render,HttpResponse

from django import forms

from django.forms import fields

import chunk

# Create your views here.
#联合唯一

class Form1(forms.Form):
    img=fields.FileField()
    # username=fields.CharField(
    #     max_length=32
    #
    # )
    # email =fields.CharField(
    #     max_length=32)
    def clean_username(self):
        print('this is clean_')
        return self.cleaned_data['username']
    def clean(self):
        value_dict=self.cleaned_data
        username=value_dict.get('username')
        email=value_dict.get('email')
        if username=='ye' and email=='hai':
            print('this is clean')
            return value_dict
def index(request):
    if request.method=='GET':
        obj=Form1()
        return render(request,'index.html',{'obj':obj})
    if request.method=='POST':
        
        obj=Form1(request.POST,request.FILES)#和传来的文件一同进行实例化
        if obj.is_valid():
            print('hahah')
            img=obj.cleaned_data.get('img')
            print(img.name)
            return HttpResponse('提交成功')
        else:
            return render(request,'index.html',{'obj':obj})
        # img = request.FILES.get('img')
        # f=open(img.name,'wb')
        # for i in img.chucks():
        #     f.write(i)
        #
        # f.close()
        #
        #
        # return HttpResponse('hello')
views

 

  

posted @ 2018-10-03 15:38  brownbearye  阅读(128)  评论(0)    收藏  举报