Django Form component Upload file

Source: Internet
Author: User

Uploading files

Note: The form submission file must have a parameter enctype= "Multipart/form-data"

Normal upload:

URLs

URL (r ' ^f1/', views.f1), url (r ' ^f2/', views.f2),

Views

DEF f1 (Request):    if Request.method = = "GET":        return render (Request, ' f1.html ')    else:        import os #导入os模块        #request. get/post  /files mode. Get () takes value to go to the value of the file Name=fafafa        file_obj=request. Files.get ("Fafafa")  #拿到一个文件对象        f=open (os.path.join (' Static ', file_obj.name), ' WB ') #将文件名加入到static目录下        For chunk in File_obj.chunks ():  #chunk块 file size, loop file_obj file object. Chunks            f.write (chunk) #写到文件里面去        f.close (        # return HttpResponse ("...")        return render (Request, ' f1.html ')

Html:

<! DOCTYPE html>
Form component upload:

Views

Class F2form (Form):    user=fields. Charfield ()    fafafa=fields. Filefield () 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)  #以POST的方式获取到文件的所有对象        if Obj.is_valid ():  #校验拿取的文件对象           # Print (obj.cleaned_data)            print ( Obj.cleaned_data.get (' Fafafa '). Name) #校验成功 Gets the Fafafa file name of the uploaded file object            print (Obj.cleaned_data.get (' Fafafa '). Size) # Gets the Fafafa size of the file object return        render (request, ' f2.html ', {' obj ': obj})  #错误信息的时候 return to the front page to continue uploading

Html:

<! DOCTYPE html>

  

Django Form component Upload file

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.