How To Upload and Download Files in Django

Django REST Framework is a robust and flexible toolkit for building Web APIs. Django allows the user to work at their own ease. In Django a user can create a table and make changes in that table even without writing a single SQL Query, isn’t it amazing? In this blog we will learn another interesting feature i.e. How to upload and download files in Django. It is so easy that once you learn you will find it’s a piece of cake. Let’s have a sneak peek about models first.

How To Upload and Download Files in Django

What is a Model ?

A table in our database is represented by the classes in our models. Every member of the class is a field of the table. We create models in the app > models.py file. Example of a model is shown below:-

Models.py

from django.db import models
# Create your models here.
class Employee(models.Model):
    name=models.CharField(max_length=50)
    salary=models.IntegerField()

Here Employee is the table name, name and salary are the attributes of the table, where name can store only character value whose maximum length is 50 and salary can store only integer value. In Django there are different fields for different kinds of data.

Implementation

Step 1. Create Django Project

We are first going to create a django project, an app inside that project by following the below steps:-

  1. Create a Django project by running the given command in the cmd or terminal.
django admin startproject blogdownloadfiles

2. Create an app in that django-project.

python manage.py startapp downloadfiles

3. Add your app name in installed apps.

Settings.py

INSTALLED_APPS = [
    ‘ downloadfiles’, 
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
Step 2. Add files and Folder to the Django Project

We need to create a template folder in the django folder and a urls.py file in the app folder. In addition with this we also need to create a media root so that we can provide path to the uploaded media files in our project

  1. Create a new folder in the django folder(here, blogdownloadfiles) save it with the name template.

2. Add the path for this template folder in blogdownloadfiles > settings.py .

Settings.py

import os
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'template')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

3. Create a new file in the app folder(here,downloadfiles) save it with the name urls.py .

4. Add path for this url.py file in blogdownloadfiles > urls.py .

Urls.py

from django.contrib import admin
from django.urls import path,include
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('downloadfiles.urls'))
]

5. Provide a new folder where you are going to store all media files uploaded by the user or uploaded to the database, by adding the following command in the respective files.

Settings.py

STATIC_URL = '/static/'
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR,'media')

Urls.py

from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('downloadfiles.urls'))
]
urlpatterns+=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Step 3.  Upload and Download Files

We are first going to add our database to our project. In settings.py add the below code according to your database in DATABASES.

  1. Add database

Settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'blogdownloadfiles',
        'USER': 'postgres',
        'PASSWORD':"2320",
        'HOST': 'localhost'
    }
}

2. Create a model in the app folder > models.py with the fields of your choice.

Models.py

Create a model in the app folder > models.py with the fields of your choice.
from django.db import models
# Create your models here.
class upload(models.Model):
    title=models.CharField(max_length=50)
    upload=models.FileField(upload_to="media")

3. Migrate Model

Run the below code to migrate your model into your database.

python manage.py makemigrations
python manage.py migrate

4. Add function in app folder >views.py 

Here the first function index is used to render the starting page where, the user will fill the forms. Second function index2 is used to submit the form created in the index html page to our model upload. After saving the model we are going to call all the objects from the model and render to the index2 html page.

Views.py

from django.shortcuts import render
from django.contrib.auth.models import User,auth
from .models import upload
# Create your views here.
def index(request):
    return render(request,'index.html')
def index1(request):
    if request.method=='POST':
        title=request.POST['title']       
        upload1=request.FILES['upload']
        object=upload.objects.create(title=title,upload=upload1)
        object.save()  
    context=upload.objects.all()
    return render(request,'index1.html',{'context':context})

5. Create Url path for the function in downloadfiles(your_app_name)>urls.py.

Urls.py

from django.urls import path
from . import views
urlpatterns = [
    path("",views.index,name="index"),
    path("index1",views.index1,name="index1")
]

6. Create a html file, here we had created 2 html file

1. INDEX.HTML :-   Here in this file we had created a form with method equals to post and specify the action or the URL to relocate after the user clicks on the submit button. One thing to be noted is that enctype equals multipart/form-data should be specified because it is an important step.

Index.html

<html>
<head>
        <title>BlogSecureMedia</title>
</head>
<body>
        <h1>Blog Secure Model</h1>
        {% for i in object %}
        <h1>Title:</h1><p>{{object.title}}</p><br>
        <h1>pdf file:</h1><button ><a href="{{i.pdf.url}}">Click to view</a></button><br>
        {% endfor %}
</body>
</html>

Output :-

How To Upload and Download Files in Django
Index.html

2. INDEX1.HTML:- Here, this file is loaded when the user clicks the submit button in the index.html page. Here we passed all the objects of our model which specifies the title and URL of the uploaded file. If you focus on the anchor tag, I had passed the URL of the file in HREF and specified the keyword download inside it, so that when the user clicks the link instead of redirecting to a new page, it will download the file.

Index1.html

<html>
<head>
    <title>Download Files</title>
</head>
<body>
    {% for i in context %}
    <h1>Title:{{i.title}}</h1>
    <h1>DOWNLOAD THE FILE FROM HERE<a href="{{i.upload.url}}" download>{{i.title}}</a></h1>
    {% endfor %}
</body>
</html>

Output :-

How To Upload and Download Files in Django
Index1.html
How To Upload and Download Files in Django
Downloaded File after clicking the above link

Quick Revision:-

  1. Create your Django project folder.
  2. Create an app folder in the Django project folder.
  3. Add template folder in the Django folder and provide its path in django_folder > settings.py.
  4. Add file named as urls.py in the app folder and provide its path in django_project > urls.py.
  5. Provide a media folder path
  6.  Add the function in app_folder > views.py.
  7. Provide the URL path in app> urls.py to the functions created in views.py.
  8. Create HTML files in the django_project > template.

Conclusion

I hope this blog will be useful for you and helps you to understand each and every step. Hope all your doubts get cleared. Best of Luck and Thank you.