Prerequisites:
Before practicing the script of this tutorial, you have to complete the following tasks.
- Install the Django version 3+ on Ubuntu 20+ (preferably)
- Create a Django project
- 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.
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.
Add the app name in the INSTALLED_APP part of the settings.py file.
…..
'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
# 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
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
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
# 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
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.