Home >>Django Tutorial >Django File Upload

Django File Upload

Django File Upload

Django provides a built-in library and methods for uploading a file to the server.

The forms.FileField() method is used to create a file input and submit the file to the server. The HTML form tag must contain enctype="multipart/form-data" property.

Let's see an example of uploading a file to the server in django.

Template (index.html)


<body>  
<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>  
</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)


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)


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

Upload Script (functions.py)


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

Now, we will create a directory upload to store the uploaded file in it.

Initially, this directory will be empty. We can upload a file to it and later on it will contain the uploaded file.

Start Server

python manage.py runserver


No Sidebar ads