Django1.8: how to upload a file using a form, django1.8 form

Source: Internet
Author: User

Django1.8: how to upload a file using a form, django1.8 form

Python has many different Web frameworks. Django is the most representative heavyweight player. Many successful websites and apps are based on Django.

Django is an open-source Web application framework written in Python.

In django, we can use the Form class to process the Form. By instantiating the Form and rendering it in the template, we can easily complete the Form requirements and adopt the django Form processing method, this can help us save a lot of work, for example, the verification cannot be empty, or the input must conform to a certain pattern, which is very convenient to process, you do not need to write code to verify the data correctness of the Form. Therefore, it is common in development. Form provides many Form fields, such as dates and text types, if you are familiar with the basic html, it will be very easy to learn, so today we do not want to describe the fields of each form one by one. Today we only talk about uploading form files, this type is special and requires special processing. Let's create a simple instance:

First, we use Form to create a simple Form:

class UserForm(forms.Form):username = forms.CharField(required=False)headImg = forms.FileField()class UserForm(forms.Form):username = forms.CharField(required=False)headImg = forms.FileField()

This form has two fields, requiring the user to enter the user name and upload a file or image.

Next we will put it in the template for rendering. Now we can see a basic form. The view function is as follows:

Def register (request): if request. method = "POST": uf = UserForm (request. POST, request. FILES) if uf. is_valid (): # return HttpResponse ('OK') else: uf = UserForm () return render (request, 'register.html ', {'U': uf }) def register (request): if request. method = "POST": uf = UserForm (request. POST, request. FILES) if uf. is_valid (): # return HttpResponse ('OK') else: uf = UserForm () return render (request, 'register.html ', {'U': uf })

This function determines whether the user's request is a POST request. If the request is correct and the verification is valid, OK is returned, and our Upload File Code is placed between the correct verification and the returned OK, because only after the file is successfully uploaded can OK be returned, we will say that if it is a GET request, an empty form will be directly displayed for the user to input.

Processing the uploaded file is to generate a file to the server and write the content of the uploaded file to the new file. Therefore, the basic function of the file is as follows: the object receiving the uploaded file is a parameter, open a local file, read the file from the uploaded file, and write it into the new file. The Code is as follows:

def handle_uploaded_file(f):with open('/server/testform/upload/' + f.name, 'wb+') as destination:for chunk in f.chunks():destination.write(chunk)def handle_uploaded_file(f):with open('/server/testform/upload/' + f.name, 'wb+') as destination:for chunk in f.chunks():destination.write(chunk)

With this processing function for uploading files, we can further improve our view functions. The final code is as follows:

def register(request):if request.method == "POST":uf = UserForm(request.POST, request.FILES)if uf.is_valid():handle_uploaded_file(request.FILES['headImg'])return HttpResponse('ok')else:uf = UserForm()return render(request, 'register.html', {'uf': uf})def register(request):if request.method == "POST":uf = UserForm(request.POST, request.FILES)if uf.is_valid():handle_uploaded_file(request.FILES['headImg'])return HttpResponse('ok')else:uf = UserForm()return render(request, 'register.html', {'uf': uf})

This completes the upload of a file.

The above is a small Editor to introduce you to django1.8 using form upload files, I hope to help you, if you have any questions, please leave a message, the small editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

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.