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.

<form method="POST" class="post-form" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="save btn btn-default">Save</button>

Form (

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 (

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():
            return HttpResponse("File uploaded successfuly")
        student = StudentForm()
        return render(request,"index.html",{'form':student})

Specify URL (

from django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
    path('index/', views.index),

Upload Script (

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

def handle_uploaded_file(f):
    with open('myapp/static/upload/', 'wb+') as destination:
        for chunk in f.chunks():

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 runserver


django file upload 1

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

django file upload 2
Related Tutorial
Follow Us #