Python

How to Download the File in Django?

The download option is a general requirement for any website like the online book, free application software, free games, etc. Th site’s users can download the necessary files on their device if the download feature is implemented for the site. The file can be downloaded after executing a particular URL or clicking the download link and getting permission from the user. The ways of downloading a text file without any download link and a PDF file using the download link in the Django app will be shown in this tutorial.

Prerequisites:

Before practicing the script of this tutorial, you have to complete the following tasks.

  1. Install the Django version 3+ on Ubuntu 20+ (preferably)
  2. Create a Django project
  3. Run the Django server to check the server is working correctly or not.

Setup a Django App:

Run the following command to create a Django app named downloadapp.

$ python3 manage.py startapp downloadapp

Run the following command to create the user for accessing the Django database. If you have created the user before then, you don’t need to run the command.

$ python3 manage.py createsuperuser

Add the app name in the INSTALLED_APP part of the settings.py file.

INSTALLED_APPS = [
    …..
    'downloadapp'
]

Create a folder named templates inside the downloadapp folder and set the template’s location of the app in the TEMPLATES part of the settings.py file.

    {
….
            'DIRS': ['/home/fahmida/django_pro/dopwnloadapp/templates'],
             ….
      },
]

Download a Text File:

Modify the views.py file that is inside the downloadapp folder with the following script. The download_file() function will download a text file named text.txt for a particular URL path. The file has opened for reading at the beginning of the script. The mime type and header information have been set to download the file.

views.py

# Import mimetypes module
import mimetypes
# import os module
import os
# Import HttpResponse module
from django.http.response import HttpResponse


def download_file(request):
    # Define Django project base directory
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    # Define text file name
    filename = 'test.txt'
    # Define the full file path
    filepath = BASE_DIR + '/downloadapp/Files/' + filename
    # Open the file for reading content
    path = open(filepath, 'r')
    # Set the mime type
    mime_type, _ = mimetypes.guess_type(filepath)
    # Set the return value of the HttpResponse
    response = HttpResponse(path, content_type=mime_type)
    # Set the HTTP header for sending to browser
    response['Content-Disposition'] = "attachment; filename=%s" % filename
    # Return the response value
    return response

Now, open the urls.py file from the Django project and update the file with the following script. The text file will download if the path, ‘download/’ is used after the base URL.

urls.py

# Import path module
from django.urls import path
# Import views
from downloadapp import views

# Set path for download
urlpatterns = [
    path('download/', views.download_file),
]

Open the browser and execute the following URL that will open the download dialog box for the user.

http://localhost:8000/download

The file will be downloaded if the user clicks on the OK button after selecting the Save File option.

Download PDF File Using the Template:

A template will be required to create if you want to add the download option with the download link. Create an HTML file named file.html with the following script to display the download link in the browser to download a PDF file. According to the hyperlink that is used in the script will download the CF.pdf file.

file.html

<html>
    <title>Download File</title>
</head>
<body>
<enter>
   <h1>Download File using Django</h1>
   <a href="{% url 'download_pdf_file' filename='CF.pdf' %}">Download PDF</a>
</center>
</body>
</html>

Create another view file named views2.py with the following script. The download_pdf_file() function has been defined in the script to download a file using the download link. The filename will be passed as the second argument value of this function. The file has opened for reading in binary mode for the PDF file. If the value of the filename argument is empty, then the file.html file will be displayed in the browser to show the download link.

views2.py

# Import mimetypes module
import mimetypes
# import os module
import os
# Import HttpResponse module
from django.http.response import HttpResponse
# Import render module
from django.shortcuts import render

# Define function to download pdf file using template
def download_pdf_file(request, filename=''):
    if filename != '':
        # Define Django project base directory
        BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        # Define the full file path
        filepath = BASE_DIR + '/downloadapp/Files/' + filename
        # Open the file for reading content
        path = open(filepath, 'rb')
        # Set the mime type
        mime_type, _ = mimetypes.guess_type(filepath)
        # Set the return value of the HttpResponse
        response = HttpResponse(path, content_type=mime_type)
        # Set the HTTP header for sending to browser
        response['Content-Disposition'] = "attachment; filename=%s" % filename
        # Return the response value
        return response
    else:
        # Load the template
        return render(request, 'file.html')

Update the urls.py file with the following script to download a particular PDF file using the download link.

urls.py

# Import path module
from django.urls import path
# Import views and views2
from downloadapp import views, views2

# Set path for download
urlpatterns = [
    path('download/', views.download_file),
    path('downloadpdf/', views2.download_pdf_file, name='download_pdf_file'),
    path('downloadpdf//', views2.download_pdf_file, name='download_pdf_file'),
]

Open the browser and execute the following URL that will display the file.html in the browser.

http://localhost:8000/downloadpdf

If the user clicks on the download link, the CF.pdf will be passed as the value of the filename argument.

If this file exists in the base location of the app, then the following dialog box will appear. The user can open the file in the browser or the document viewer before the download or download the file directly without opening it by selecting the Save File option and pressing the OK button.

Conclusion:

Adding a download option for text and PDF files in the Django application was shown in this tutorial using a simple script. The new Django users will get an idea to add a download option without and with a download link in the Django app after reading this tutorial.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.