Django File Upload

File upload to the server using Django is a very easy task. Django provides built-in library and methods that help to upload a file to the server.

The forms.FileField() method is used to create a file input and submit the file to the server. While working with files, make sure the HTML form tag contains enctype=”multipart/form-data” property.

Let’s see an example of uploading a file to the server. This example contains the following files.

Template (index.html)

It will create an HTML form which contains a file input component.


  1. <body>  
  2. <form method="POST" class="post-form" enctype="multipart/form-data">  
  3.         {% csrf_token %}  
  4.         {{ form.as_p }}  
  5.         <button type="submit" class="save btn btn-default">Save</button>  
  6. </form>  
  7. </body>  

Form (forms.py)

from django import forms  

class StudentForm(forms.Form):  

    firstname = forms.CharField(label="Enter first name",max_length=50)  

    lastname  = forms.CharField(label="Enter last name", max_length = 10)  

    email     = forms.EmailField(label="Enter Email")  

    file      = forms.FileField() # for creating file input

View (views.py)

Here, one extra parameter request.FILES is required in the constructor. This argument contains the uploaded file instance.

from django.shortcuts import render  

from django.http import HttpResponse  

from myapp.functions.functions import handle_uploaded_file  

from myapp.form import StudentForm  

def index(request):  

    if request.method == 'POST':  

        student = StudentForm(request.POST, request.FILES)  

        if student.is_valid():  

            handle_uploaded_file(request.FILES['file'])  

            return HttpResponse("File uploaded successfuly")  

    else:  

        student = StudentForm()  

        return render(request,"index.html",{'form':student})

Specify URL (urls.py)


  1. from django.contrib import admin  
  2. from django.urls import path  
  3. from myapp import views  
  4. urlpatterns = [  
  5.     path('admin/', admin.site.urls),  
  6.     path('index/', views.index),  
  7. ]  

Upload Script (functions.py)

This function is used to read the uploaded file and store at provided location. Put this code into the functions.py file. But first create this file into the project.

def handle_uploaded_file(f):  

    with open('myapp/static/upload/'+f.name, 'wb+') as destination:  

        for chunk in f.chunks():  

            destination.write(chunk)

Now, create a directory upload to store the uploaded file. Our project structure looks like below.

django file upload

Initially, this directory is empty. so, let’s upload a file to it and later on it will contain the uploaded file.

Start Server

python manage.py runserver  

Output

django file upload 1

Submit this form and see the upload folder. Now, it contains the uploaded file.

django file upload 2

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *